Accessing inherited scope with Controller As approach

前端 未结 3 1204
名媛妹妹
名媛妹妹 2020-12-04 23:45

With the original way to define controllers, accessing the parent\'s scope was fairly trivial, since the child scope prototypically inherits from its parent

3条回答
  •  忘掉有多难
    2020-12-05 00:08

    After researching, I came to the following realization:

    Controller-As approach is NOT a substitute for using $scope. Both have their place, and can/should be used together judiciously.

    1. $scope does exactly what the name implies: i.e. it defines ViewModel properties on the $scope. This works best for sharing scope with nested controllers that can use the $scope to drive their own logic or to change it.
    2. Controler-As defines the entire controller object as a ViewModel with a named scope (via the controller's alias). This works best only in the View (but not other controllers), if the View decides if it wants to reference a specific controller ViewModel.

    Here's an example:

    var app = angular.module('myApp', []);
    
    // Then the controllers could choose whether they want to modify the inherited scope or not:
    app.controller("ParentCtrl", function($scope) {
        this.prop1 = {
          v: "prop1 from ParentCtrl"
        };
        $scope.prop1 = {
          v: "defined on the scope by ParentCtrl"
        };
      })
      .controller("Child1Ctrl", function($scope) {})
      .controller("Child2Ctrl", function($scope) {
        // here, I don't know about the "pc" alias
        this.myProp = $scope.prop1.v + ", and changed by Child2Ctrl";
      });
    
    
    
      
    I know about the "pc" alias: {{pc.prop1.v}}
    I only care about my own ViewModel: {{ch2.myProp}}

提交回复
热议问题