本文介绍了用例在angularjs $控制器服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angularjs文档给为$控制器服务的使用:
$控制器(构造函数,当地人);

任何人都可以关注一些光在这2点:


  1. 何时使用 $控制器服务。请提供一些使用案例。

  2. 有关'本地人'参数传递给它的详细信息。


解决方案

您可以创建要在$范围内执行到一个控制器可以被命名为'CommonCtrl常用功能

  angular.module(应用,[])。控制器('CommonCtrl',['$范围',函数($范围){
      VAR自我=这一点;
      $ scope.stuff1 =功能(){      }      $ scope.stuff2 =功能(){      }
      self.doCommonStuff =功能(){
               //此处常见的东西
               $ scope.stuff1();
               $ scope.stuff2();      };
      返回自我;
}]);

和注入该控制器的其它控制器让说'TestCtrl1就像

  angular.module(应用,[])。控制器('TestCtrl1',['$范围,$控制器,函数($范围,$控制器){
        VAR commonCtrl = $控制器('CommonCtrl',{$范围:$范围}); //传递电流范围commmon控制器
        commonCtrl.doCommonStuff();
}]);

下面,由CommonCtrl需要在$控制器服务的第二个参数,我们传递的依赖关系。所以doCommonStuff方法将使用TestCtrl1控制器的范围。

Angularjs docs give the usage of $controller service as:$controller(constructor, locals);

Can anyone focus some light on these 2 points:

  1. When to use $controller service. Please provide some use case.
  2. Details about 'locals' parameter passed to it.
解决方案

You can create common functions which are to be executed on $scope into one controller may be named 'CommonCtrl'.

angular.module('app',[]).controller('CommonCtrl', ['$scope', function($scope){
      var self = this;
      $scope.stuff1 = function(){

      }

      $scope.stuff2 = function(){

      }
      self.doCommonStuff = function(){
               // common stuff here
               $scope.stuff1();
               $scope.stuff2();

      };
      return self;
}]);

And inject this controller in other controllers let say 'TestCtrl1' like

angular.module('app',[]).controller('TestCtrl1', ['$scope','$controller', function($scope, $controller){
        var commonCtrl = $controller('CommonCtrl',{$scope: $scope}); // passing current scope to commmon controller
        commonCtrl.doCommonStuff();
}]);

Here, the in second argument of $controller service, we are passing dependencies that are required by CommonCtrl. So the doCommonStuff method will use TestCtrl1 controller's scope.

这篇关于用例在angularjs $控制器服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:57