控制器之间通信的正确方法是什么?
我目前正在使用一种可怕的软糖包括window:
function StockSubgroupCtrl($scope, $http) {
$scope.subgroups = [];
$scope.handleSubgroupsLoaded = function(data, status) {
$scope.subgroups = data;
}
$scope.fetch = function(prod_grp) {
$http.get('/api/stock/groups/' + prod_grp + '/subgroups/').success($scope.handleSubgroupsLoaded);
}
window.fetchStockSubgroups = $scope.fetch;
}
function StockGroupCtrl($scope, $http) {
...
$scope.select = function(prod_grp) {
$scope.selectedGroup = prod_grp;
window.fetchStockSubgroups(prod_grp);
}
}
Run Code Online (Sandbox Code Playgroud) 我熟悉以下方法来实现控制器之间的通信.
还有其他人吗?有更好的方法/最佳实践吗?
$broadcast/$emit.controller("Parent", function($scope){
$scope.$broadcast("SomethingHappened", {..});
$scope.$on("SomethingElseHappened", function(e, d){..});
})
.controller("Child", functions($scope){
$scope.$broadcast("SomethingElseHappened", {..});
$scope.$on("SomethingHappened", function(e, d){..});
})
.controller("AnotherChild", functions($scope){
$scope.$on("SomethingHappened", function(e, d){..});
});
Run Code Online (Sandbox Code Playgroud)
或者,从视图:
<button ng-click="$broadcast('SomethingHappened', data)">Do Something</button>
Run Code Online (Sandbox Code Playgroud)
好处:
缺点:
$rootScope,使用<div ng-controller="Parent">
<div ng-controller="Child">
<div ng-controller="ChildOfChild">
<button ng-click="someParentFunctionInScope()">Do</button>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
或者,在代码中
.controller("ChildOfChild", function($scope){
$scope.someParentFunctionInScope();
});
Run Code Online (Sandbox Code Playgroud)
好处:
缺点:
$rootScope,使用$watch控制器仅响应范围暴露数据的变化,从不调用函数.
.controller("Parent", function($scope){
$scope.VM = {a: "a", b: "b"};
$scope.$watch("VM.a", function(newVal, oldVal){
// react
}); …Run Code Online (Sandbox Code Playgroud)