我有一个包含应用程序模型的服务:
angular.module('adminClient').factory('myApi', function () {
var model = {};
model.myObject = {
label: 'New York City'
};
return {
model: function () {
return model;
}
};
});部分/控制器可以访问模型,并可以设置新的myObject:
angular.module('adminClient').controller('MySelectNetworkCtrl', function ($scope, myApi) {
$scope.myObject = myApi.model().myObject;
});除此之外,我还有一个指令可以显示包含在myObject中的标签:
angular.module('nav').directive('myTopBar', function(myApi) {
return {
restrict: 'E',
replace: true,
scope: {},
templateUrl: 'nav/directive/my-top-bar/my-top-bar.html',
link: function(scope, element, attrs, fn) {
scope.myObject = myApi.model().myObject;
}
};
});下面是HTML:
<div id="my-top-bar">
<span ng-bind="myObject"></span>
</div>当我运行应用程序时,标签显示得很好(纽约市),但是一旦控制器更改了myObject,指令中的标签就保持不变。我也可以在Chrome角度范围检查器中看到这一点。
你知道如何让指令显示当前的值,即使在控制器改变之后?
发布于 2014-10-14 23:29:58
这完全取决于控制器如何更新模型对象。由于您的代码
scope.myObject = myApi.model().myObject;
获取这个特定的模型对象,只要更改了模型对象的myObject属性,它就能正常工作。
但如果控制器这样做
myApi.model().myObject= {}; //or any new object
现在,服务返回的模型具有不同的myObject,指令模型也不同。因此,更改不起作用。
相反,在do指令中:
scope.myObject = myApi.model(); // bind to model
并相应地更新指令模板中的绑定。看看它是否起作用
发布于 2016-09-06 14:18:20
检查此plunkr
如果您希望修改控制器中的myObject,并且希望此更改反映在您的my-top-bar指令中,该指令随后从myApi服务更新指令的作用域,那么您应该这样做。
更新控制器中的myObject,然后还通过setter方法在服务中更新它。
// Doing this will update your scope.myObject but
// will not change the moObject in your service
$scope.myObject = {
label: 'updated label'
};
// This will update your service, and anyone making a myApi.myApi.model() after this will get an updated myObject
myApi.setModel($scope.myObject);
// Notify directive of the change
$scope.$broadcast('updateDirective');在工厂里:
angular.module('plunker').factory('myApi', function() {
var model = {};
model.myObject = {
label: 'New York City'
};
return {
model: function() {
return model;
},
setModel: function(newModel) {
model.myObject = newModel;
}
};
});最后,指令:
angular.module('plunker').directive('myTopBar', function(myApi) {
return {
restrict: 'E',
replace: true,
scope: {},
templateUrl: 'top-bar.html',
link: function(scope, element, attrs, fn) {
console.log('in directive link', myApi.model().myObject);
scope.myObject = myApi.model().myObject;
},
controller: function($scope) {
$scope.$on('updateDirective', function() {
console.log('updating the scope of directive so that ng-bind works');
$scope.$apply(function() {
$scope.myObject = myApi.model().myObject;
console.log($scope.myObject);
});
});
}
};
});https://stackoverflow.com/questions/26363927
复制相似问题