【发布时间】:2015-03-16 03:42:27
【问题描述】:
我试图找出控制器/指令之间共享属性或状态的“首选”或“角度方式”。有几种方法可以实现这一点,但我想保持最佳实践。以下是一些关于如何实施的平庸示例:
1.使用 $scope.$watch
// The parent controller/scope
angular.module('myModule').controller('parentController', ['$scope', function($scope) {
$scope.state = {
myProperty: 'someState'; // Default value to be changed by some DOM element
};
}]);
// The child controller/scope.
angular.module('myModule').controller('childController', ['$scope', function($scope) {
$scope.$watch('state.myProperty', function (newVal) {
// Do some action here on state change
});
}]);
编辑:根据下面的答案,这是不好的做法,应该避免。它是不可测试的,并且会产生不必要的 DOM 依赖。
2。使用 $broadcast
// The parent controller
angular.module('myModule').controller('parentController', ['$scope', function($scope) {
var myProperty = 'someState';
$scope.setState = function (state) {
myProperty = state; // Set by some other controller action or DOM interaction.
$scope.$broadcast('stateChanged', state); // Communicate changes to child controller
}
}]);
// The child controller.
angular.module('myModule').controller('childController', ['$scope', function($scope) {
$scope.$on('stateChanged', function (evt, state) {
// Do some action here
}
}]);
编辑:同样不好的做法,因为您需要知道控制器在 DOM 中的位置,以便确定使用 $broadcast(DOM 下方)或 $emit(DOM 上方)的天气.
3.使用服务
angular.module('myModule').factory('stateContainer', [function () {
var state = {
myProperty: 'defaultState'
},
listeners = [];
return {
setState: function (newState) {
state.myProperty = newState;
angular.forEach(listeners, function (listener) {
listener(newState);
});
},
addListener: function (listener) {
listeners.push(listener);
}
}
}]);
// The parent controller
angular.module('myModule').controller('parentController', ['$scope', 'stateContainer', function($scope, stateContainer) {
$scope.setState = function (state) {
stateContainer.setState(state);
};
}]);
// The child controller.
angular.module('myModule').controller('childController', ['$scope', 'stateContainer', function($scope, stateContainer) {
stateContainer.addListener(function (newState) {
// Do some action here
});
}]);
我可能在这里错过了一些方法,但你明白了。我正在尝试找到 最佳 方法。虽然冗长,但我个人倾向于此处列表中的#3。但我来自广泛使用侦听器的 Java 和 jQuery 背景。
编辑:下面的答案很有见地。有人谈到使用require 指令配置在父/子指令之间共享状态。另一个讨论直接向范围共享服务或服务属性。我相信根据需要,它们在 Angular 的最佳实践中是正确的还是不是最佳实践。
【问题讨论】: