我对angular很新,我试图用工厂替换一些范围数据结构但是依赖注入导致了问题。请帮忙
https://jsfiddle.net/bennacer860/k8js1o4m/1/
angular.module('flapperNews', [])
.factory('posts', [function() {
var o = {
posts: []
};
return o;
}]);
angular.module('flapperNews', [])
.service('myService', function() { /* ... */ })
.controller('MyController', ['myService', function(myService) {
// Do something with myService
console.log("test");
}]);
angular.module('flapperNews', [])
.controller('MainCtrl', ['$scope', 'posts', function($scope, posts) {
$scope.test = 'Hello world!';
// $scope.posts = [
// {title: 'post 1', upvotes: 5},
// {title: 'post 2', upvotes: 2},
// {title: 'post 3', upvotes: 15},
// {title: 'post 4', upvotes: 9},
// {title: 'post 5', upvotes: 4}
// ];
$scope.posts = posts.posts;
$scope.addPost = function() {
if (!$scope.title || $scope.title === '') {
return;
}
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: 0
});
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
};
}]);
答案 0 :(得分:4)
在第一个[]
之后删除angular.module('flapperNews', [])
。
传递参数会告诉angular创建模块的新实例,因此会破坏任何先前的实例。