从服务/工厂绑定变量控制器 [英] Binding variables from Service/Factory to Controllers

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

问题描述

我有将在一个或多个控制器,通过服务改变使用的变量。
在这种情况下,我已经建立控制器之间的保持这个变量在内存中的服务,与大家共享。

I have a variable that will use at one or more Controllers, changed by Services. In that case, I've build a service that keep this variable in memory, and share between the controllers.

的问题是:每该变量的变化,在控制器中的变量实时ins't更新时间。

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

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

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

---注意, {{} countService} {{} countFactory} 从不更新时我递增计数的值。

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

怎么着我绑定服务/在控制器厂变量$ scope.variable?我做错了吗?

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

推荐答案

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

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.

厂址:

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

控制器:

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

查看:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆