在angular1.x中继承控制器

时间:2017-11-02 05:54:13

标签: javascript angularjs

对于angular1.6,我的情况是60%左右的控制器逻辑相同。在这种情况下,如何将继承应用于控制器逻辑? 我经历了http://blog.mgechev.com/2013/12/18/inheritance-services-controllers-in-angularjs/http://jasonwatmore.com/post/2014/03/25/angularjs-a-better-way-to-implement-a-base-controller

并编写了一个示例代码,以便在我的案例中应用,但这不起作用。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <script type="text/javascript" src="https://unpkg.com/angular@1.6.6/angular.min.js">
  </script>
</head>
<body ng-app="test">

<div class="" ng-controller="Child1 as ctrl1">
  <input type="text" name="name" value="">
  <button type="button" name="button" ng-click="ctrl1.clickMethod()">ClickA</button>
</div>

<div class="" ng-controller="Child2 as ctrl2">
  <input type="text" name="name" value="">
  <button type="button" name="button" ng-click="ctrl2.clickMethod()">ClickB</button>
</div>

<script type="text/javascript">

  angular.module('test',[])
    .controller('Base', function(){

      var sharedMethod = function(arg) {
        console.log('shared method called with ' + arg);
      }
    })
    .controller('Child1', function($scope, $controller) {

      $controller('Base', { $scope : $scope});
      var ctrl1 = this;
      var clickMethod = function() {
        this.sharedMethod(41);
      };
    })
    .controller('Child2', function($scope, $controller) {

      $controller('Base', { $scope : $scope});
      var ctrl2 = this;
      var clickMethod = function() {
          this.sharedMethod(42);
      };
    })
</script>
</body>
</html>

sharedMethod是我希望与两个不同的视图共享的东西,具有不同的控制器。

此外,在这个例子中,我创建了没有任何视图的控制器(Base),是否可以使用角度?

1 个答案:

答案 0 :(得分:3)

您的代码中存在一些错误,因为您已经定义了进行以下更改所需的功能:

 angular.module('test',[]).controller('Base', function($scope){

 $scope.sharedMethod = function(arg) {
    console.log('shared method called with ' + arg);
  }
})
.controller('Child1', function($scope, $controller) {

  $controller('Base', { $scope : $scope});
  var ctrl1 = this;
  ctrl1.clickMethod = function() {
    $scope.sharedMethod(41);
  };
})
.controller('Child2', function($scope, $controller) {

  $controller('Base', { $scope : $scope});
  var ctrl2 = this;
  ctrl2.clickMethod = function() {
      $scope.sharedMethod(42);
  }

});

你必须正确调用函数才能使其正常工作。