另一种注入方式 Angular

Another way to inject in Angular

我有一个模板,我正在更改注入双侧的方式。它有 'classic' 注入方式。我想用紧凑的形式替换它。我不能做这些代码行。我试过了,但我无法理解结构。因为我习惯了另一种形式。有人可以帮助我吗?

(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
  }
}
})();

这是一个如何注入依赖项的示例。

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);
                    }
                )
        }

    }
}]);

我认为这也是您所指的方式。希望这有帮助。