我正在使用 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/