问题
I'm trying to offer a SORT functionality amongst all my modules and I'd like to know integrate this. Does Angular support some sort of mixin?
I'd like the mixin to inject new properties (models) and methods to the controller associated to the module. These properties and methods should only use their associated controller's scope.
I know I could use underscore _.extend or jQuery.extend() , but I'd like to know if there's a cleaner way to do this in a true Angular spirit.
Regards.
回答1:
One year later:
You can use scope inheritance! You can have a main controller with all the functionality you want to share and then you can specify child controllers in the following way:
HTML:
<body ng-controller="MainCtrl">
<div id="wrapper" ng-controller="SectionCtrl">
...
</div>
</body>
MainCtrl:
function MainCtrl($scope) {
$scope.sorter = { array: [], sort: function() { } };
}
SectionCtrl:
function SectionCtrl($scope) {
$scope.sorter.array = [1,2,3];
$scope.sorter.sort();
}
No need to declare $scope.sorter since MainCtrl has already declared it. Scope inheritance in angular works pretty much like scope inheritance in Javascript.
回答2:
Yes! and it is very simple.
I can give you an example how to achieve that:
(...)
.controller('ParentCTRL', ['$scope', function($scope) {
$scope.base_func= function() {
//Do something
};
}]);
.controller('ChildrenCTRL', ['$controller', '$scope', function($controller, $scope) {
$controller('ParentCTRL', {$scope: $scope});
// Now you can access base_fun() from here
}]);
.controller('SecondChildrenCTRL', ['$controller', '$scope', function($controller, $scope) {
$controller('ParentCTRL', {$scope: $scope});
// Now you can access base_fun() from here
}]);
回答3:
I'm not sure exactly what you're trying to do, but it sounds like you want a Service, which is then dependency-injected into your controllers and directives.
来源:https://stackoverflow.com/questions/13253448/angular-mixins-integration