我有一个更新我的奖励范围的控制器:
控制器1
.controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {
$scope.updateAwardScope = function () {
resource = TokenRestangular.all('award');
resource.getList()
.then(function (awards) {
$scope.awards = awards;
})
}
}])
控制器2
我有另一个控制器2,其中包含一个位于此控制器范围之外的单击事件。下面的控制器是否可以从控制器1调用$scope.updateAwardScope
功能?
.controller('MainController', function ($rootScope, $scope) {
$scope.updateAwardScopeClick = function () {
// somehow call function from controller 1
}
});
答案 0 :(得分:1)
我发现使用工厂/服务模式是在角度应用程序中重用代码的一种非常有效的方法。对于这种特殊情况,您可以创建一个AwardFactory,将其注入您的控制器,然后调用更新函数。即
<强> AwardFactory 强>
myApp.factory('AwardFactory', ['TokenRestangular', function(TokenRestangular.all) {
var factory = {
awards: []
};
factory.update = function() {
resource = TokenRestangular.all('award');
resource.getList().then(function (awards) {
factory.awards = awards;
});
return factory.awards; // You can skip the return if you'd like that
};
return factory;
}]);
<强> YourController 强>
.controller('MainController', function ($rootScope, $scope, AwardFactory) {
$scope.updateAwardScopeClick = function () {
AwardFactory.update();
}
});
希望它有所帮助!
答案 1 :(得分:1)
您可以使用角度广播和接收
控制器1
.controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {
$scope.updateAwardScope = function () {
resource = TokenRestangular.all('award');
resource.getList()
.then(function (awards) {
$scope.awards = awards;
$rootScope.broadcast("update.awards");
})
}
}])
控制器2
.controller('MainController', function ($rootScope, $scope) {
$rootScope.$on('update.awards', function(){
$scope.updateAwardScopeClick();
});
$scope.updateAwardScopeClick = function () {
// somehow call function from controller 1
}
});