【发布时间】:2016-04-07 21:32:51
【问题描述】:
这是一个我不习惯问的问题,但我觉得这是了解我正在努力解决的问题的唯一方法。如下图所示,有两个函数app.controller() 和app.factory(),对我来说它们似乎是相等的,即使我删除了一个部分,该函数也不会执行它的预期任务。
plunker 链接:click here(相关文件为 script.js)
这两个函数有什么区别,为什么我不能只有其中一个?我知道必须有一个简单的解释。
app.controller('MainCtrl', ['$scope', 'ItemsService', function ($scope, ItemsService) {
$scope.newItem = { PlateNumber: '', Description: '', Price: 0 };
$scope.currentItem = null;
$scope.items = ItemsService.getItems();
$scope.addItem = function () {
ItemsService.addItem(angular.copy($scope.newItem));
$scope.newItem = { PlateNumber: '', Description: '', Price: 0 };
};
$scope.updateItem = function (id) {
ItemsService.updateItem(id);
};
$scope.removeItem = function (id) {
ItemsService.removeItem(id);
};
}]);
对
app.factory('ItemsService', ['$firebase', 'FIREBASE_URI', function ($firebase, FIREBASE_URI) {
var ref = new Firebase(FIREBASE_URI);
var items = $firebase(ref);
var getItems = function () {
return items;
};
var addItem = function (item) {
items.$add(item);
};
var updateItem = function (id) {
items.$save(id);
};
var removeItem = function (id) {
items.$remove(id);
};
return {
getItems: getItems,
addItem: addItem,
updateItem: updateItem,
removeItem: removeItem
}
}]);
【问题讨论】:
-
虽然两者看起来很相似,但实际上并不相似,您是否尝试阅读 angular 文档?你必须有一个控制器,你不需要一个工厂...docs.angularjs.org/guide/providers更多链接:stackoverflow.com/questions/14324451/…另一个:jsfiddle.net/k3phygpz
-
服务是单例的,控制器不是。这是一个开始。
-
使用你最喜欢的那个(在这种情况下)
标签: javascript angularjs controller firebase plunker