问题描述
我对以下代码有疑问:Plunkr.
I have a problem with the following code: Plunkr.
当我单击按钮时,ng-click
在范围内更改变量 var1
.但显然这个变量没有在视图中更新,这是我用 UI 路由器创建的.看起来作用域已经复制到同一个控制器中了.
When I click the button, the ng-click
changes the variable var1
in scope. But apparently this variable is not updated in view, which I have created with UI Router. It looks like the scope have been copied inside the same controller.
问题在两种情况下消失:当我在我的视图中使用 {{$parent.var1}}
而不是 {{var1}}
时,或者当我从我的状态中删除 controller: 'MainCtrl'
声明.
The problem disappears in two situations: when I use {{$parent.var1}}
instead of {{var1}}
from inside my view, OR when I remove controller: 'MainCtrl'
declaration from my state.
任何人都可以澄清发生了什么以及如何避免此类问题?我喜欢删除控制器声明的解决方案,但 Angular UI Router 将如何确定使用哪个控制器?
Can anyone clarify what's going on and how to avoid such problems? I like the solution with removing the controller declaration but how Angular UI Router will figure out which controller to use?
推荐答案
控制器和一些向 dom 添加元素的指令创建自己的作用域 (ng-if
, ng-switch
、ng-repeat
、ng-view
等).您可以使用 AngularJS Batarang chrome 扩展来帮助调试它们.值是继承的,但在子作用域中设置值会破坏继承.您可以创建自己的服务,也可以使用从父作用域继承的对象,只要您在继承的对象上设置属性就可以了.由于您在控制器中设置值,因此我使用 ||
仅在没有继承值的情况下初始设置值.(plnkr):
Controllers and some directives that add elements to the dom create their own scope (ng-if
, ng-switch
, ng-repeat
, ng-view
etc.). You can use the AngularJS Batarang chrome extension to help debug them. The values are inherited, but setting the value in a child scope breaks the inheritance. You can create your own service, or you can use an object inherited from a parent scope and as long as you're setting properties on the inherited object you'd be fine. Since you're setting the value in your controller I use ||
to only set the value initially if an inherited value isn't there. (plnkr):
app.controller('MainCtrl', function($scope, globals) {
$scope.var1 = 1;
$scope.obj = $scope.obj || {var1: 1};
$scope.g = globals; // for access in the page
$scope.onClick = function() {
globals.var1++;
$scope.var1++;
$scope.obj.var1++;
};
});
app.service('globals', function() {
this.var1 = 1;
return this;
});
这篇关于使用 Angular UI Router 在视图中单击 ng-click 时不会更新范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!