AngularJS:使用call(或apply)的Controller继承

前端之家收集整理的这篇文章主要介绍了AngularJS:使用call(或apply)的Controller继承前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我在尝试使控制器更可重用时发现的.

app.factory('BaseController',function(myService) {
  return function(variable) {
    this.variable = variable;
    this.method = function() {
      myService.doSomething(variable);
    };
  };
})

.controller("ChildController1",function($scope,BaseController) {
  BaseController.call($scope,"variable1");
})

.controller("ChildController2","variable2");
});

现在我可以在我的HTML中做这样的事情(例如在ng-controller =“ChildController1”里面):ng-click =“method()”

代码很简单.但我不知道它是如何运作的(它是什么样的模式?)并且这样做是否是一个好习惯?

解决方法

您的解决方案或多或少地工作如下:

app.factory('mixinBaseController',function(myService) {
  return function (scope,variable) {
    angular.extend(scope,{
      variable: variable;
      method: function() {
        myService.doSomething(variable);
      }
    });
  };
})

.controller("ChildController1",mixinBaseController) {
  mixinBaseController($scope,"variable2");
});

你能看到吗你能明白吗?通过你的.call($scope,…)只是将上下文(this)设置为真正的$scope,这样BaseController只是用属性函数扩展你的范围.

这只是为了演示代码的工作原理.

要实现更像JavaScript的继承,请参阅:

> Can an AngularJS controller inherit from another controller in the same module?
> AngularJS controller inheritance
> AngularJS Inheritance Patterns
> Two Approaches to AngularJS Controller Inheritance

您还应该看看AngularJS 1.2中引入的“controllerAs” syntax.我强烈建议使用controllerAs.这也应该有助于实现控制器的继承.

猜你在找的Angularjs相关文章