刚开始使用AngularJS并试图找出在控制器内的变量发生变化时监听事件的最佳做法。我已经得到它的唯一方法是发射,如下所示。指令监听控制器变量变化
例如:
var app = angular.module("sampleApp", [])
app.controller("AppCtrl", function($scope){
$scope.elements = [
{
name: "test"
}
]
$scope.addElement = function() {
$scope.elements.push({
name: "test" + $scope.elements.length
})
$scope.$emit('elementsChanged', $scope.elements);
}
})
app.directive('render', function() {
var renderFunc = function() {
console.log("model updated");
}
return {
restrict: 'E',
link: function(scope, element, attrs, ngModel) {
scope.$on('elementsChanged', function(event, args) {
renderFunc();
})
}
}
})
这似乎有点靠不住的,而且我觉得我的工作对角点。我试图在模型上使用$ watch,但这似乎不起作用。任何帮助,将非常感激,谢谢!
您的目标是通知其他控制器该变量已更改?要么? – KayakDave
只是在这一点指示,只是注意到我的标题有一个奇怪的错字,哈哈。 – dardo
检查了这一点,看看它是你在找什么:http://stackoverflow.com/questions/17138868/how-to-trigger-a-directive-when-updating-a-model-in-angularjs – KayakDave