我使用工厂作为单例。我想从该工厂访问 Controller 的范围。它归结为以下代码:
angular.module('foo', [])
.controller('fooCtrl', function($scope, testFac) {
$scope.example = "I wanna change";
testFac.change = function(change){
$scope.example = change;
}
})
.factory('testFac', function($timeout){
var testFac= {}
$timeout(function(){
testFac.change("You changed")
}, 3000)
return testFac;
})
目前我在 Controller 中声明该函数,因为这样我就处于正确的范围内,并且我可以从工厂调用该函数。但这似乎不是一个非常优雅的解决方案。 有更好的方法来解决这个问题吗? 出于测试目的,请参阅此 fiddle
最佳答案
I use a factory as a singleton
工厂/服务/提供商是单例
I want to access the scope of a controller from this factory.
在工厂内使用范围进行操作并不是一个好习惯。在 Angular 中, Controller 的作用域仅用于将 View 绑定(bind)到 Controller 。
关于您的代码:
.factory('testFac', function($timeout){
var testFac= {}
$timeout(function(){
testFac.change("You changed")
}, 3000)
return testFac;
})
这不是工厂的目的。您可以编写第二个 Controller 或指令
Is there a better way to solve this?
是的,您可以使用$broadcast
Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.
关于javascript - 从工厂访问范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46810008/