[英]AngularJS $scope is not updating in DOM
I have the following codes : 我有以下代码:
The state (lets just make it short for simplicity purposes) 国家 (为简单起见,我们简单说明)
.state('foo', {
url: '/foo',
templateUrl: 'path/to/template.html',
controller:'fooCtrl',
})
The controller 控制器
controller = function($scope){
// not the actual code
$scope.barCount
}
template.html template.html
<div>
<span>{{ barCount }}</span> // this is updating properly
</div>
Other html partial 其他html偏
<div ng-controller="fooCtrl">
<span>{{ barCount }}</span> // this is **NOT** updating properly
</div>
I have a scope
variable on my controller . 我的控制器上有一个
scope
变量。 The 2-way binding is working fine on the template that was declared on the state
together with the controller . 双向绑定在与控制器一起在
state
上声明的模板上正常工作。 But not on the other partial template where in I binded the controller using the ng-controller
. 但不是在其他部分模板中,我使用
ng-controller
对控制器进行绑定。
Is this some kind of bug? 这是某种错误吗? Or am I missing something?
或者我错过了什么? Thanks.
谢谢。
You have one Controller but two instances of that controller. 您有一个Controller但该控制器有两个实例。 Each time you use ng-controller or declare it in differents views a new instance is created, so all controllers are in differents scopes.
每次使用ng-controller或在不同视图中声明它时,都会创建一个新实例,因此所有控制器都在不同的范围内。 The best way to share data between controller are services, because these are singleton, so they have one instance.
在控制器之间共享数据的最佳方式是服务,因为它们是单例,因此它们有一个实例。 Example:
例:
angular.module('app')
.factory('fooService', [function(){
var bar = 'Shared Data';
return {
getBar: function(){
return bar;
}
};
}])
.controller('FooController', ['fooService', function(fooService){
this.barCount = fooService.getBar();
// or use $scope.barCount = fooService.getBar();
}];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.