从服务/工厂到控制器的绑定变量

Dei*_*zan 69 angularjs angularjs-directive

我有一个将由一个或多个控制器使用的变量,由服务更改.在这种情况下,我构建了一个服务,将此变量保存在内存中,并在控制器之间共享.

问题是:每次变量发生变化时,控制器中的变量都不会实时更新.

我创建这个小提琴帮助.http://jsfiddle.net/ncyVK/

---注意当我递增count的值时,{{countService}}或者{{countFactory}}永远不会更新.

如何将Service/Factory变量绑定到Controller中的$ scope.variable?我做错了什么?

jus*_*sio 117

你不能绑定变量.但是您可以绑定包含此变量的变量访问器或对象.这是固定的jsfiddle.

基本上你必须传递一些东西,它可以返回/或保持当前值.例如

厂:

app.factory('testFactory', function(){
    var countF = 1;
    return {
        getCount : function () {

            return countF; //we need some way to access actual variable value
        },
        incrementCount:function(){
           countF++;
            return countF;
        }
    }               
});
Run Code Online (Sandbox Code Playgroud)

控制器:

function FactoryCtrl($scope, testService, testFactory)
{
    $scope.countFactory = testFactory.getCount; //passing getter to the view
    $scope.clickF = function () {
        $scope.countF = testFactory.incrementCount();
    };
}
Run Code Online (Sandbox Code Playgroud)

视图:

<div ng-controller="FactoryCtrl">

    <!--  this is now updated, note how count factory is called -->
    <p> This is my countFactory variable : {{countFactory()}}</p>

    <p> This is my updated after click variable : {{countF}}</p>

    <button ng-click="clickF()" >Factory ++ </button>
</div>
Run Code Online (Sandbox Code Playgroud)

  • @Aram不,工厂也是单身人士; Angular的所有服务都是单身人士.在模块上注册工厂函数时,它将在调用时创建服务实例. (4认同)
  • 因此,通过将函数作为testFactory.getCount传递而不是调用它,并在UI中调用它,您已绑定了服务值.如果您使用$ scope.countFactory = testFactory.getCount(),那么在初始化时只调用一次函数并且没有任何约束?如果价值发生变化,以后不会更新? (2认同)