首页 新闻 会员 周边

angularjs的问题

0
[已关闭问题] 关闭于 2015-12-26 12:24

服务注入的时候到底应该注入到module里面还是controller里面

天上囧在天上飞的主页 天上囧在天上飞 | 初学一级 | 园豆:6
提问于:2015-11-02 14:17
< >
分享
所有回答(2)
0

module上,多个controller可用。angular的注入其实是将你的服务作为一个全局对象的属性,然后用的时候,去get一下,这就导致如果服务重名,是会被覆盖的。

幻天芒 | 园豆:37175 (高人七级) | 2015-11-02 14:48
0

将服务用作控制器的依赖和将服务用作其他服务的依赖很类似。

因为Javascript是一种动态语言,依赖注入系统无法通过静态类型来知道应该注入什么样的服务(静态类型语言就可以)。所以,你应该$inject的属性来指定服务的名字,这个属性是一个包含这需要注入的服务的名字字符串的数组。名字要和服务注册到系统时的名字匹配。服务的名称的顺序也很重要:当执行工场函数时传递的参数是依照数组里的顺序的。但是工场函数中参数的名字不重要,但最好还是和服务本身的名字一样,下面展示了这样的好处:formatDate

function myController($loc, $log) {
this.firstMethod = function() {
 // use $location service
 $loc.setHash();
};
this.secondMethod = function() {
 // use $log service
 $log.info('...');
};
}
// which services to inject ?
myController.$inject = ['$location', '$log'];

index.html:

<!doctype html>
<html ng-app="MyServiceModule">
  <head>
    <script src="http://code.angularjs.org/angular-1.0.2.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body>
    <div ng-controller="myController">
      <p>Let's try this simple notify service, injected into the controller...</p>
      <input ng-init="message='test'" ng-model="message" >
      <button ng-click="callNotify(message);">NOTIFY</button>
    </div>
  </body>
</html>

script.js:

angular.
 module('MyServiceModule', []).
 factory('notify', ['$window', function(win) {
    var msgs = [];
    return function(msg) {
      msgs.push(msg);
      if (msgs.length == 3) {
        win.alert(msgs.join("\n"));
        msgs = [];
      }
    };
  }]);

function myController(scope, notifyService) {
  scope.callNotify = function(msg) {
    notifyService(msg);
  };
}

myController.$inject = ['$scope','notify'];

测试:

it('should test service', function() {
    expect(element(':input[ng\\:model="message"]').val()).toEqual('test');
});
徐大腿 | 园豆:420 (菜鸟二级) | 2015-11-17 16:35
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册