angularjs share data config between controllers

后端 未结 4 951
予麋鹿
予麋鹿 2020-11-28 15:52

I\'m wondering what could be a good way to share directive between controller. I\'ve got ie two directives to use in different controller with different configuration the fi

4条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 16:07

    Consider the method described by this post: Extending AngularJS Controllers Using the Mixin Pattern

    Instead of copying your methods out of a service, create a base controller that contains those methods, and then call extend on your derived controllers to mix them in. The example from the post:

    function AnimalController($scope, vocalization, color, runSpeed) {
    
        var _this = this;
    
        // Mixin instance properties.
        this.vocalization = vocalization;
        this.runSpeed = runSpeed;
    
        // Mixin instance methods.
        this.vocalize = function () {
            console.log(this.vocalization);
        };
    
        // Mixin scope properties.
        $scope.color = color;
    
        // Mixin scope methods.
        $scope.run = function(){
            console.log("run speed: " + _this.runSpeed );
        };
    }
    

    Now we can mixin AnimalController into DogController:

    function DogController($scope) {
    
        var _this = this;
    
        // Mixin Animal functionality into Dog.
        angular.extend(this, new AnimalController($scope, 'BARK BARK!', 'solid black', '35mph'));
    
        $scope.bark = function () {
            _this.vocalize(); // inherited from mixin.
        }
    }
    

    And then use DogController in our template:

    Dog

    The controllers in this example are all in the global space and are included in the markup as follows.

    
    
    
    
    
    
    

    I haven't tested it, but I don't see why the following wouldn't work:

    var myApp = angular.module('myApp', [])
    
    .controller('AnimalController', ['$scope', 'vocalization', 'color', 'runSpeed', function ($scope, vocalization, color, runSpeed) { /* controller code here */}]);
    
    .controller('DogController', ['$scope', '$controller', function($scope, $controller) {
        var _this = this;
    
        // Mixin Animal functionality into Dog.
        angular.extend(this, $controller('AnimalController', {
             $scope: scope,
             vocalization: 'BARK BARK!', 
             color: 'solid black', 
             runSpeed:'35mph' 
        }));
    
        $scope.bark = function () {
            _this.vocalize(); // inherited from mixin.
        }
    }]);
    

    see: docs for $controller service

提交回复
热议问题