2
我有一個模板,我正在改變注入偏序的方法。它有'經典'的注入方式。我想用緊湊的形式替換它。我不能做這些代碼行。我試過了,但我無法理解結構。因爲我習慣於另一種形式。有人能幫助我嗎?Angular的另一種注入方法
(function() {
'use strict';
angular.module('app.data')
.factory('postResource', postResource)
.factory('postsUtils', postsUtils);
postResource.$inject = ['$resource'];
function postResource($resource) {
return $resource('/api/posts/:id', {id: '@id'}, {
update: {
method: 'PUT'
}
});
}
postsUtils.$inject = ['postResource'];
function postsUtils(postResource) {
function postsDuringInterval(posts, days) {
var today = new Date();
var interval = 86400000 * days;
var postsDuringInterval = [];
posts.forEach(function(post) {
var postDate = new Date(post.date);
today - postDate < interval && postsDuringInterval.push(post);
});
return postsDuringInterval;
}
function recent(posts, postsNum) {
posts.sort(function(a, b) {
if (a.date < b.date) return 1;
else if (a.date == b.date) return 0;
else return -1;
});
return posts.slice(0, postsNum || 1);
}
function lastEdited(posts) {
var lastEdited = posts[0];
posts.forEach(function(post) {
lastEdited = lastEdited.date < post.date ? lastEdited : post;
});
return lastEdited;
}
return {
postsDuringInterval: postsDuringInterval,
lastEdited: lastEdited,
recent: recent
}
}
})();
謝謝,但我不明白我的代碼。這些功能是連接到控制器還是服務? – panagulis72
該服務。你可以調用服務的方法,因爲它被注入。 *注意,這些也應該是單獨的文件。還要注意'this'和'self'。他們是不同的和重要的理解。 – Drew1208
這是正確的嗎? https://plnkr.co/edit/LOugzgRN5K5JZPwb7IgR?p=preview – panagulis72