加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 16:57:00 所属栏目:安全 来源:网络整理
导读:这是我在尝试使控制器更可重用时发现的. app.factory('BaseController',function(myService) { return function(variable) { this.variable = variable; this.method = function() { myService.doSomething(variable); }; };}).controller("ChildController1
这是我在尝试使控制器更可重用时发现的.

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.这也应该有助于实现控制器的继承.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读