javascript - 从工厂访问范围

标签 javascript angularjs

我使用工厂作为单例。我想从该工厂访问 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/

相关文章:

javascript - 为白板应用程序发送一个大数据包还是许多较小的数据包?

javascript - ng-grid是否支持按行进行单元格过滤( Angular 过滤)

javascript - 带有 ionic 框架的 instagram feed 无限滚动不会在转发器错误中停止重复

javascript - 加载数据、插入数据并滑动切换

javascript - typescript 错误 :Property 'contains' does not exist on type 'Element' . ?

javascript - 为什么以及何时我们在 JavaScript 中使用对象解构?

javascript - 如何使用chart js或其他库绘制甘特图

javascript - karma.conf.js Uncaught ReferenceError : google no defined

angularjs - Angular $scope 数据不会更新

javascript - 在 ng-repeat 中绑定(bind) ngmodel 的正确方法