Access ng-model data outside of the controller

后端 未结 1 1644
情书的邮戳
情书的邮戳 2020-12-20 09:20

I have written the below code



  
user.nam         


        
相关标签:
1条回答
  • 2020-12-20 09:41

    You could use a publish subscribe pattern for this. That way you avoid putting the variable on the rootscope.

    function Ctrl($scope) {
        $scope.onDate = "12/01/2015";
    
        $scope.$watch('onDate', function(newValue, oldValue) {
         $scope.$emit('onDateChanged', newValue);
        });
     }
    
    function Ctrl2($scope, $rootScope) {
       $scope.onDate = "";
    
       $rootScope.$on('onDateChanged', function(event, value) {
       $scope.onDate = value;
       });
    }
    

    Your controller will get called when your template loads.

    <span ng-controller="Ctrl">
    <input type="text" ng-model="onDate">
    </span>  
    <pre>user.name = <span ng-controller="Ctrl2" ng-bind="onDate"></span></pre>
    

    Now how does it work:

    Angular does not share scopes. Each controller has its own seperate scope. So in order to keep our child scopes up to date we need to somehow throw an event on which our children subscribe to. This can be done in two ways.

    $scope.$emit or $rootScope.$broadcast

    The difference between the two is subtle.

    $scope.$emit wil send the event up the chain. so for instance consider this scope hierarchy.

    rootscope
        scope1 ---> subscribes to the emit $scope.$on
          scope2 ---> performs a $scope.$emit
            scope3 ---> subscribes to the emit $scope.$on
    

    only scope1 will catch the event. since $scope.$emit goes up the chain. this is a way to only update specific scopes. although what is mostly done is this.

    rootscope
            scope1 ---> subscribes to the emit $rootScope.$on
              scope2 ---> performs a $scope.$emit
                scope3 ---> subscribes to the emit $rootScope.$on
    

    we inject $rootScope in the controller of scope1 and scope3 and subscribe to the emit on the rootscope. Since the rootscope is the highest scope it will always catch the $emit from scope2. This is a way to only send the event to specific controllers wich subscribe on the rootscope.

    lastly we can also do this:

     rootscope
                scope1 ---> subscribes to the emit $scope.$on
                  scope2 ---> performs a $rootScope.$broadcast
                    scope3 ---> subscribes to the emit $scope.$on
    

    we are now shouting on the rootscope and instead of moving up like emit, broadcast works down the chain. This is the equivalent of shouting in a room and everyone who doesnt have his ear protectors on will hear it. in essence everyone who subscribes on their local scope to the event that broadcast is sending

    0 讨论(0)
提交回复
热议问题