Javascript AngularJS$scope未在DOM中更新
我有以下代码: 状态(为了简单起见,让我们把它缩短) 控制器Javascript AngularJS$scope未在DOM中更新,javascript,angularjs,angular-controller,Javascript,Angularjs,Angular Controller,我有以下代码: 状态(为了简单起见,让我们把它缩短) 控制器 controller = function($scope){ // not the actual code $scope.barCount } template.html <div> <span>{{ barCount }}</span> // this is updating properly </div> <div ng-controller="fo
controller = function($scope){
// not the actual code
$scope.barCount
}
template.html
<div>
<span>{{ barCount }}</span> // this is updating properly
</div>
<div ng-controller="fooCtrl">
<span>{{ barCount }}</span> // this is **NOT** updating properly
</div>
{{barCount}}//这是正确更新的
其他html部分
<div>
<span>{{ barCount }}</span> // this is updating properly
</div>
<div ng-controller="fooCtrl">
<span>{{ barCount }}</span> // this is **NOT** updating properly
</div>
{{barCount}}//这是**未**正确更新
我的控制器上有一个范围
变量。双向绑定在模板上正常工作,该模板与控制器一起在状态上声明。但在另一个部分模板上,我使用ng控制器
绑定了控制器
这是某种臭虫吗?还是我遗漏了什么?谢谢。您有一个控制器,但该控制器有两个实例。每次使用ng控制器或在不同视图中声明它时,都会创建一个新实例,因此所有控制器都在不同的作用域中。
在控制器之间共享数据的最佳方式是服务,因为它们是单例的,所以它们只有一个实例。
例如:
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();
}];
我对AngularJS真的很陌生,但你不应该在div中使用{{}
?你想保留count
的最后一个值,并且你想在其他状态下保持相同吗?@shrestha_aj噢,谢谢你指出这一点。打字错误。:)@PankajParkar我真的不明白你想说什么,但我想要的是,两个模板都应该根据控制器的值相应地更新。GreenFoxx否。你的猜测是错误的。如果你在不同的部分之间共享同一个控制器。它们都将有控制器的新实例。第一部分中的范围变量更改不会在其他控制器中复制。因为它们是不同的实例。您必须创建一个服务来共享应用程序中的数据