本文介绍了将变量从服务/工厂绑定到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我创建了这个 Fiddle 来提供帮助.http://jsfiddle.net/ncyVK/

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

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

解决方案

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

基本上你必须向作用域传递一些可以返回/或保存当前值的东西.例如

工厂:

app.factory('testFactory', function(){无功计数F = 1;返回 {获取计数:函数(){返回计数F;//我们需要某种方式来访问实际的变量值},增量计数:函数(){计数F++;返回计数F;}}});

控制器:

function FactoryCtrl($scope, testService, testFactory){$scope.countFactory = testFactory.getCount;//将getter传递给视图$scope.clickF = 函数 () {$scope.countF = testFactory.incrementCount();};}

查看:

<!-- 现在更新了,注意计数工厂是如何调用的--><p>这是我的 countFactory 变量:{{countFactory()}}</p><p>这是我在点击变量后更新的:{{countF}}</p><button ng-click="clickF()" >工厂++ </button>

I have a variable that will be used by one or more Controllers, changed by Services.In that case, I've built a service that keeps this variable in memory, and share between the controllers.

The problem is: Every time that the variable changes, the variables in the controllers aren't updated in real time.

I create this Fiddle to help. http://jsfiddle.net/ncyVK/

--- Note that the {{countService}} or {{countFactory}} is never updated when I increment the value of count.

How can I bind the Service/Factory variable to $scope.variable in the Controller? What I'm doing wrong?

解决方案

You can't bind variables. But you can bind variable accessors or objects which contain this variable. Here is fixed jsfiddle.

Basically you have to pass to the scope something, which can return/or holds current value. E.g.

Factory:

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;
        }
    }
});

Controller:

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

View:

<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>

这篇关于将变量从服务/工厂绑定到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:44