将$ rootScope仅部分注入工厂

时间:2014-10-14 22:13:24

标签: angularjs

在这个plunker中,工厂会注入$ rootScope。

吸虫不是我的。

当我将$ rootScope注入我自己的工厂时,它不起作用。

为什么它在plunker中起作用?在哪里写的我可以在工厂注入$ rootScope?

http://plnkr.co/edit/2hoMTaloeqbgSe81VQLF?p=preview

var app = angular.module('plunker', []);

app.factory('messageService', function($rootScope) {


alert($rootScope);
  var messenger = {
    messages: [],
    identity: 0,
    addMessage: function(text, caller) {

      this.identity +=1;
      var id = this.identity,
       message = {
        text: caller + text,
        id: id
      };

      this.messages.push(message);
      $rootScope.$broadcast('messageAdded');
    }
  };

  return messenger;
});

app.controller('Controller1', function($scope, messageService) {
  $scope.messages1 = messageService.messages;
  $scope.post = {
    text: ''
  };

  $scope.postMessage = function() {
    console.log($scope.post);
    messageService.addMessage($scope.text, "controller 1");
  };

  $scope.$on('messageAdded', function() {
    $scope.messages1 = messageService.messages;
  });
});



app.controller('Controller2', function($scope, messageService) {
  $scope.messages2 = messageService.messages;
  $scope.post = {
    text: ''
  };

  $scope.postMessage = function() {
    messageService.addMessage($scope.text, "controller 2");
  };

  $scope.$on('messageAdded', function() {
    $scope.messages2 = messageService.messages;
  });
});

这只是我自己的示例代码,我不知道为什么没有注入$ rootScope:

'use strict';
angular.module('test').factory('MyViewModel', function ($rootScope) {

    function MyViewModel(items ) {

        var self = this;
        self.items = items ;

     }


    return( MyViewModel);
});

1 个答案:

答案 0 :(得分:0)

$rootScope肯定是在这里注入的,但它只会在你的服务被实例化时发生..只有当你将它注入控制器或页面上使用的其他服务时才会发生。

见下文,添加到$rootScope的变量,由控制器继承:



angular.module('test', [])
  .factory('MyViewModel', function($rootScope) {

    $rootScope.hello = 'Hello!';

    function MyViewModel(items) {

      var self = this;
      self.items = items;

    }

    return MyViewModel;
  })
  .controller('MyCtrl', function(MyViewModel) {
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test">
  <div ng-controller="MyCtrl">{{hello}}</div>
</div>
&#13;
&#13;
&#13;