javascript - 使用 angular.extend() 作为 Controller 和重写函数

标签 javascript angularjs inheritance angular-controller

我正在使用 Angular 1.4.8 并尝试扩展 Controller 。原始 Controller 和扩展 Controller 都非常相似,但我想在扩展 Controller 中覆盖一个功能。

angular.module('app').controller('ControllerOne', function() {

    var vm = this;

    vm.data = {};

    vm.callSayHello = function() {
        vm.sayHello();
    }

    vm.sayHello = function() {
        console.log('Hello from ControllerOne.');
    }
});

angular.module('app').controller('ControllerTwo', ['$scope', function($scope) {

    angular.extend(vm, $controller('OrdersAddController', { $scope: $scope }));

    // I do not want to override vm.callSayHello(), so I don't redeclare that function.

    // This is what I want to override.
    vm.sayHello = function() {
        console.log('Hello from ControllerTwo.');

        // Some other extra handling.
    }
}]);

<button type="button" ng-click="ctrl.callSayHello()">Click Me</button>

看起来我可以覆盖 ControllerOne功能在 ControllerTwo 。但对于这种特殊情况,我想要覆盖的函数 vm.sayHello() ,不是直接从单击等事件调用,而是由另一个函数 vm.callSayHello() 调用。 。

所以当 vm.callSayHello() 时会发生什么从 ControllerOne 调用或ControllerTwo ,也称为 vm.sayHello() ,但它总是调用 ControllerOne 上的函数尽管在 ControllerTwo 中重新声明。

希望这是有道理的。但有没有一种方法可以覆盖 vm.sayHello()函数位于 ControllerTwo

最佳答案

你可以这样做:

function mySmth(vm, $scope) {
  // no vm = this
 vm.smth = ...
}

现在:

function baseCtrl($scope) {
  var vm = this;
  mySmth(vm, $scope);
}

function etendedCtrl($scope) {
  var vm = this;
  mySmth(vm, $scope);
  vm.smth = ...// something new
}

但这并不花哨,实际上很好的建议是 - 只是不要扩展 Controller ...如果您有通用功能 - 将它们投入服务或单独的 Controller 。

关于javascript - 使用 angular.extend() 作为 Controller 和重写函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43475043/

相关文章:

javascript - 选择加载哪个JS文件不加载文件

javascript - jQuery/sessionStorage : flicker effect on hidden element, 以编程方式隐藏

javascript - Angular - 如何在开始时设置点击事件

javascript - ngRoute 不改变 HTML。

AngularJs 和全局命名空间

java - 如何在数组中存储子类的对象?

c++ - 我们不能从基类 : why? 继承什么

javascript - 无法更改 html 表格单元格的颜色

linux - CentOS 6.5 如何让新文件继承父文件夹所有权?

javascript - 在 JavaScript 中暂停 YouTube iFrame API