对于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),它没有任何视图,它可以用角吗?
发布于 2017-11-02 06:14:50
在定义函数的方式上,代码中有一些错误,您需要进行以下更改:
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);
}
});你必须正确地调用函数才能让它正常工作。
https://stackoverflow.com/questions/47068490
复制相似问题