Angular Mixins integration

旧时模样 提交于 2019-12-25 02:12:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!