angularJS中的服务就是一个小例子。

时间:2016-10-03 08:52:49

标签: angularjs

我正在阅读一系列文档来了解服务和工厂。 遇到了这个工作代码。

  var app = angular.module('plunker', []);
   app.value('cnt', 7);
    app.service('foo', function(cnt) {
      this.cnt = ++cnt;
      this.inc = function(quan) {
        this.cnt += quan;
      };
    });
    app.controller('MainCtrl', function($scope, cnt, foo) {
      $scope.cnt = cnt;
      $scope.foo = foo;
      $scope.inc = function() {
        $scope.foo.inc(1); // why $scope used here
      };
    });
    app.controller('TangentCtrl', function($scope, foo) {
      $scope.jump = function() {
       foo.inc(5);  // Why $scope not used here and why it doesnot work when I add scope
      };
    });

在TangentCtrl控制器$ scope.jump函数中,它没有使用$ scope来访问foo.inc,你可以在我评论的代码中看到。 我认为这里有一些我不理解的概念,任何人都可以启发我。

3 个答案:

答案 0 :(得分:1)

这是因为您在声明foo

时注入controller
app.controller('TangentCtrl', function($scope, foo) {...}

在控制器功能中,您将获得foo服务的实例。

理想情况下,您应该按如下方式编写控制器。因此,当您在控制器本身中获得服务实例时,为什么需要$scope来访问inc函数?

app.controller('TangentCtrl', ['$scope', 'foo', function($scope, foo) { 
    ....
}]);

答案 1 :(得分:1)

查看此代码

 app.service('foo', function(cnt) {
  this.cnt = ++cnt;
  this.inc = function(quan) {
    this.cnt += quan;
  };
});

图片你有一个类'foo',在这个类'inc'是一个函数,你输出'foo'作为服务,在上面的'foo'可以用作两个控制器之间的连接来传递一些他们之间的数据。

所以你只是通过这一行在'TangentCtrl'中注入foo

  

app.controller('TangentCtrl',函数($ scope,foo){......});

因为你可以在前面使用没有$ scope的'foo',所以foo.inc(5);将在foo服务中调用方法inc,因此foo可以被其他控制器调用以获取值。

答案 2 :(得分:1)

var app = angular.module("myApp",[]);


function constructorFunction() {
  this.getData = function() {
    //bussiness logic
  };
}

/*
  * your are registering service called myService
  * service/factory uses singleton design pattern
  * i.e. you have an object called myService in app
*/
app.service('myService', constructorFunction);
/*
  * Here, you are passing sevice name (myService) and 
  * constructor Function (constructorFunction) to service
  * provider
  * which creates singleton object (myService)
*/


/*
  * angular uses injector to resolve dependencies 
  * your are actully tells injector to
  * add these dependencies to your controller function
*/
app.controller('myCtrl',function($scope, myService){
  /*
    * Here, you get $scope and myService
    * $scope and myService these are two different objects.
    * It is not yet compulsory to inject $scope if you 
    * use controllerAs syntax, good practice
  */
  //view specific logic
});

/*
  * Note: array syntax is useful in case of minification
  * ['$scope', 'foo', function($scope, foo){}]
  * angular maps minified variables with strings provided
  * to resolve dependencies.
*/