簡體   English   中英

無法將值分配給 Angular 工廠內的變量?

[英]Not able to assign the value to a variable inside Angular factory?

如果變量是一個數組,那么我可以將對象推入其中並在控制器中獲取值,但是如果將對象直接分配給該變量,我將無法做到

請任何人幫助我實現這一目標。

這是小提琴鏈接

角度代碼:

//angular.js example for factory vs service
var app = angular.module('myApp', []);

app.factory('testFactory', function(){
     var countF={};//= [{abc:'aaa'}];
    return {

        getCount : function () {

            return countF;
        },
        incrementCount:function(){
          //countF.push({aaaa:'jshfdkjsf'});
           countF={aaaa:'jshfdkjsf'};
            //return countF;
        }
    }               
});

function FactoryCtrl($scope,testFactory)
{
    $scope.countFactory = testFactory.getCount();
    $scope.clickF = function () {
       testFactory.incrementCount();
       // console.log($scope.countFactory);
    };
}

HTML代碼:

<div ng-controller="FactoryCtrl">

    <!--  this is never updated after count is changed! -->
    <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>

就像評論中所說的,問題出在參考文獻中,但這里是黑客:

//angular.js example for factory vs service
var app = angular.module('myApp', []);
app.factory('testFactory', function(){
    var countF={};//= [{abc:'aaa'}];
    var getCountF = function(){
        return countF;
    };
    var setCountF = function(arg){
        countF = arg;
    };
    return {

    getCount : getCountF,
    setCount : setCountF,

    incrementCount:function(){
        //countF.push({aaaa:'jshfdkjsf'});
        countF={aaaa:'jshfdkjsf'};
        //return countF;
    }
}
});

function FactoryCtrl($scope,testFactory)
{
    $scope.countFactory = testFactory.getCount();
    $scope.clickF = function () {
        testFactory.incrementCount();
        // console.log($scope.countFactory);
    };
}

快速小提琴

您的問題出在此代碼中-

 incrementCount:function(){
        //countF.push({aaaa:'jshfdkjsf'});
        countF={aaaa:'jshfdkjsf'};
        //return countF;
 }

在這里,您不是在重新創建 countF 對象的 aaa 屬性

初始化- countF = {};

添加屬性-

  right `countF.aaa = "value";`

  wrong `countF = { aaa : 'value' }`

解決方案——

incrementCount:function(){
    countF.aaaa = 'jshfdkjsf';
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM