1
我在學習AngularJS的基礎知識,我無法弄清楚爲什麼這個Factory返回一個未定義的值。這是我第一次嘗試創建和了解工廠。我在網上和互聯網上看到了很多例子,但我找不到解決方案。angularjs factory returned undefined
我想在工廠和每個不同的視圖中顯示的按鈕上創建一個字符串(顏色)的數組,以將一個字符串添加到數組。但工廠返回未定義,所以我不能將值注入控制器。
這是代碼。
的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>
JS文件(mijs.js)與控制器,工廠和$ routeProvider服務
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>
它的作品!但是,儘管我試圖理解它,但我不知道爲什麼會發生這種情況。我的意思是,爲什麼當我引用在控制器中聲明的某些東西時,我必須將「vm.Variable」(或範圍中的別名)放在工廠中,而且這種方式在工廠中的工作方式不一樣? – FranP
工廠可以生產您想要的任何類型的東西。如果你想產生一個具有屬性的對象,那麼你可以(就像在我的第一個代碼塊中那樣)。事實上,這可能是使用工廠最常用的方式,因爲它可以讓工廠有多種東西,每種都有自己的名字。因此,如果它是一個對象,就會像對待'vm.Variable'一樣將它作爲對象進行交互。 –
另一方面,你的代碼有工廠生產數組,而不是一個對象。 由於它是一個數組,它沒有.arrayColors屬性;它只有0,1,2等指數。這在工廠裏是合法的,但它有點不常見。如果你想這樣做,那麼你需要以數組的方式與它交互。 –