AngularJS controller inheritance

前端 未结 6 1117
闹比i
闹比i 2020-12-01 04:44

AngularJS has a DOM based controller inheritance, as mentioned in the angular Docs.

Base Controller

6条回答
  •  天命终不由人
    2020-12-01 05:17

    When multiple controllers need access to the same data, a service should be used. You should not rely on scope inheritance, as it restricts how you can write your HTML. E.g., in the future, you made decide that DerivedController should not be a child of BaseController.

    Your service should typically provide a public API, and hide the implementation. This makes it easier to refactor the internals.

    HTML:

    Base Controller Value: {{model.getValue()}}

    Derived Controller Value: {{model.getValue()}}

    JavaScript:

    app.factory('sharedModel', function () {
        // private stuff
        var model = {
            value: "initial Value"
        };
        // public API
        return {
            getValue:    function() { 
               return model.value; 
            },
            updateValue: function(value) {
               model.value = value;
            }
        };
    });
    
    function BaseController($scope, sharedModel) {
        $scope.model = sharedModel;
    }
    
    function DerivedController($scope, sharedModel) {
        $scope.model = sharedModel;
    }
    

    Fiddle.

    Also, I do not recommend using $rootScope for sharing between controllers.

提交回复
热议问题