我有一个简单的应用程序和几个控制器。在每个filter += ExpirationDate >= DateTime.Today
我定义了一个controller
函数。我这样做是因为我希望它可以很容易地刷新"控制器 - 只需调用"init"
函数,如下所示:init
。
换句话说,$scope.init()
中的Page_Load
事件(如果您在代码中定义它,则会在页面加载时触发该函数。
我尝试使用为每个控制器运行的.Net
函数,但我不知道如何完成此任务以完成任务。
decorator

var myApp = angular.module('myApp',[]);
myApp.decorator('$controller', ['$delegate', function ($delegate) {
return function (constructor, locals) {
var controller = $delegate.apply(null, arguments);
// Never got hear
if (locals.$scope && locals.$scope.init) {
console.log('init');
locals.$scope.init();
}
return angular.extend(function () {
return controller();
}, controller);
};
}]);
myApp.controller('ctrl1', function($scope) {
$scope.init = function() {
$scope.name = 'Superhero';
};
// I don't want to call this
$scope.init();
});
myApp.controller('ctrl2', function($scope) {
$scope.init = function() {
$scope.name = 'Mario';
};
// I don't want to call this
$scope.init();
});

答案 0 :(得分:3)
您可以将此功能添加到控制器内部的范围内。所以它将被添加到这一行
return angular.extend(function () {
return controller(); //here
}, controller);
你可以简单地保存这个值,可以调用它,比如
return angular.extend(function () {
var c = controller(); //here save controller object
if (locals.$scope && locals.$scope.init) {
console.log('init');
locals.$scope.init();
}
return c;//return controller;
}, controller);
样品:
var myApp = angular.module('myApp',[]);
myApp.decorator('$controller', ['$delegate', function ($delegate) {
return function (constructor, locals) {
var controller = $delegate.apply(null, arguments);
return angular.extend(function () {
var c = controller();
// Never got hear
if (locals.$scope && locals.$scope.init) {
console.log('init');
locals.$scope.init();
}
return c;
}, controller);
};
}]);
myApp.controller('ctrl1', function($scope) {
$scope.init = function() {
$scope.name = 'Superhero';
};
});
myApp.controller('ctrl2', function($scope) {
$scope.init = function() {
$scope.name = 'Mario';
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp">
<div ng-controller="ctrl1">
Hello, {{name}}!
</div>
<div ng-controller="ctrl2">
My name is, {{name}}!
</div>
</div>