我有一个模板,我正在改变注入家属的方式。它有经典的'注入的方式。我想用紧凑的形式替换它。我不能做这些代码。我已经尝试但我无法理解结构。因为我习惯于其他形式。有人可以帮帮我吗?
(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
}
}
})();
答案 0 :(得分:1)
以下是如何注入依赖项的示例。
var app = angular.module('myApp',
['ngRoute', 'ngSanitize', 'ui.bootstrap', 'angular-flexslider',
'ng-backstretch', 'angular-parallax', 'fitVids', 'wu.masonry', 'timer',
'uiGmapgoogle-maps', 'ngProgress']);
注入服务的控制器示例。
app.controller('ContactController',['$scope','contactService',
function($scope, contactService) {
var self = this;
self.contact = {id:null, name:"",lastName:"",email:"",subject:"",message:""};
this.submit = function(){
contactService.submit(self.contact);
self.contact = {id:null, name:"",lastName:"",email:"",subject:"",message:""};
};
}]);
工厂:
app.factory('contactService',['$http','$q', function($http,$q){
return {
submit: function (contact) {
return $http.post('/sendForm/', contact)
.then(
function (response) {
return response;
},
function (errResponse) {
console.error("Error while submitting form" + errResponse);
return $q.reject(errResponse);
}
)
}
}
}]);
我认为这也是你所指的方式。希望这会有所帮助。