簡體   English   中英

angularjs工廠返回未定義

[英]angularjs factory returning undefined

我正在學習AngularJS的基礎知識,無法弄清楚為什么這個Factory返回一個未定義的值。 這是我創建和了解工廠的第一次嘗試。 我在SO和Internet上看到了很多示例,但找不到解決方案。

我正在嘗試在工廠中創建一個字符串(顏色)數組,並在每個不同的視圖中顯示一個按鈕以向該數組添加一個字符串。 但是工廠會返回未定義的值,因此我無法將值注入控制器。

這是代碼。

的index.html

<head>
</head>

<body>
    <a href="#/">Home</a>
    <a href="#/seccion1">Seccion 1 </a>
    <div ng-view>

    </div>  
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>

    <script src="mijs.js"></script>

</body>

帶有控制器,工廠和$ routeProvider服務的JS文件( mijs.js)

var app=angular.module("myMod",['ngRoute']);

app.config(
    function($routeProvider)
    {
        $routeProvider.when('/',
            {
                controller:'ctrlHome',
                controllerAs:'home',
                templateUrl:'home.html'
            }
        );

        $routeProvider.when('/seccion1',
            {
                controller:'ctrlSeccion1',
                controllerAs:'seccion1',
                templateUrl:'seccion1.html'
            }
        );
    }//end function($routeProvider)
);//end config

app.factory("factColors",function(){
    var arrayColors=['red','green','blue'];
    return arrayColors;
}); //end factory

app.controller('ctrlHome',function(factColors) 
    {
        var home=this;
        home.arrayColors=factColors.arrayColors;
    }

);//end home controller

app.controller('ctrlSeccion1',function(factColors) 
    {
        var seccion1=this;
        seccion1.arrayColors=factColors.arrayColors;
    }
);//end seccion1 controller

這是home.html視圖

<p>home view </p>
<p ng-repeat="color in home.arrayColors">{{color}}</p>

<button ng-click="home.arrayColors.push('orange')">add color</button>

視圖seccion1.html

<p>seccion 1 view </p>
<p ng-repeat="color in seccion1.arrayColors">{{color}}</p>

<button ng-click="seccion1.arrayColors.push('purple')">add color</button>

您的工廠將直接返回陣列。 就其本身而言,這很好,但是您正在訪問它,就像它正在返回具有arrayColors屬性的對象一樣。 因此,可以將工廠更改為此:

app.factory("factColors",function(){
    return {
        arrayColors: ['red','green','blue']
    };
});

或更改與此交互的方式:

app.controller('ctrlSeccion1',function(factColors) {
    var seccion1=this;

    seccion1.arrayColors=factColors;
}

暫無
暫無

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

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