javascript - What's the recommended way to extend AngularJS controllers? -
i have 3 controllers quite similar. want have controller these 3 extend , share functions.
perhaps you don't extend controller possible extend controller or make single controller mixin of multiple controllers.
module.controller('ctrlimpladvanced', ['$scope', '$controller', function ($scope, $controller) { // initialize super class , extend it. angular.extend(this, $controller('ctrlimpl', {$scope: $scope})); … additional extensions create mixin. }]);
when parent controller created logic contained within executed. see $controller() for more information $scope
value needs passed. other values injected normally.
@mwarren, concern taken care of auto-magically angular dependency injection. need inject $scope, although override other injected values if desired. take following example:
(function(angular) { var module = angular.module('stackoverflow.example',[]); module.controller('simplecontroller', function($scope, $document) { this.getorigin = function() { return $document[0].location.origin; }; }); module.controller('complexcontroller', function($scope, $controller) { angular.extend(this, $controller('simplecontroller', {$scope: $scope})); }); })(angular);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js"></script> <div ng-app="stackoverflow.example"> <div ng-controller="complexcontroller c"> <span><b>origin controller:</b> {{c.getorigin()}}</span> </div> </div>
although $document not passed 'simplecontroller' when created 'complexcontroller' $document injected us.
Comments
Post a Comment