以下代码,特别是planetFactory部分在最初加载页面时有效。意思是,使用7个默认环创建一个新的Planet对象。但是,如果调用函数将新的Planet对象分配给$scope.planet
,则不会发生任何事情。在示例代码中,如果添加名称或直径,然后单击“创建新行星”,则不会调用planetFactory。
我对这里的工厂缺少什么?
var app = angular.module('app', ['appControllers', 'appServices']);
var appControllers = angular.module('appControllers', [])
.controller('main', ['$scope', 'planetFactory', function($scope, planetFactory) {
$scope.planet = planetFactory;
$scope.newPlanet = function () {
console.log('This part is actually executed but no factory call');
$scope.planet = planetFactory;
}
}]);
var appServices = angular.module('appServices', [])
.constant('defaultRings', 7)
.factory('planetFactory', ['defaultRings', function (defaultRings) {
console.log('Factory called, logging this message');
function Planet (rings) {
this.name;
this.diameter;
this.rings = rings;
}
return new Planet(defaultRings);
}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h3>Change the name or diameter so to confirm creating a new planet doesnt work</h3>
<div ng-app="app" ng-controller="main">
Name <input type="text" ng-model="planet.name"> <br/>
Diameter <input type="text" ng-model="planet.diameter"> <br/>
<hr/>
Planet object: <br/>
Name: {{ planet.name }} <br/>
Diameter: {{ planet.diameter }} Km <br/>
Rings: {{ planet.rings }}<br/>
<input type="button" ng-click="newPlanet()" value="Create new planet">
<br/><br/><br/>
</div>
&#13;
答案 0 :(得分:0)
找到将工厂用于此特定目的的正确方法in this excellent guide from Todd Motto:
我以前做的和他的方法之间的区别在于,工厂代码中没有使用new
关键字,工厂返回整个构造函数,然后调用new planetFactory
代码来自实际的控制器。
var app = angular.module('app', ['appControllers', 'appServices']);
var appControllers = angular.module('appControllers', [])
.controller('main', ['$scope', 'planetFactory', function($scope, planetFactory) {
$scope.planet = new planetFactory(8);
$scope.newPlanet = function() {
console.log('This part is actually executed but no factory call');
$scope.planet = new planetFactory(3);
}
}]);
var appServices = angular.module('appServices', [])
//.constant('defaultRings', 7) --> not needed
.factory('planetFactory', ['defaultRings', function(defaultRings) {
console.log('Factory called, logging this message');
function Planet(rings) {
this.name;
this.diameter;
this.rings = rings;
}
return Planet;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h3>Change the name or diameter so to confirm creating a new planet doesnt work</h3>
<div ng-app="app" ng-controller="main">
Name <input type="text" ng-model="planet.name"> <br/> Diameter <input type="text" ng-model="planet.diameter"> <br/>
<hr/> Planet object: <br/> Name: {{ planet.name }} <br/> Diameter: {{ planet.diameter }} Km <br/> Rings: {{ planet.rings }}<br/>
<input type="button" ng-click="newPlanet()" value="Create new planet">
<br/><br/><br/>
</div>