What's the difference between using function a

2019-03-06 08:12发布

问题:

I found some differences between executing function and using expression to set variable, specifically, it seems that ng-if fails to detect the changes made by expression. I don't understand why.

Pseudo-code:

if($scope.editingProfile)
  display edit section
click(backToList button)
  hide edit section

The backToList button has a ng-click attribute, when I write ng-click="backToList()" to execute $scope.backToList() in which the $scope.editingProfile is set to false it works good. But when I write ng-click="editingProfile=false" to set the variable directly, the ng-if used to hide the section won't work.

fiddle: http://jsfiddle.net/brfbtbd7/1/

回答1:

It is because ng-if directive creates a child scope. So ng-if="editingProfile" is the editing profile object on the parent which gets inherited to the child scope created by the ng-if. That is what gets displayed @ Editing {{editingProfile.name}}<br>. When you do ng-click="editingProfile=false" you are actually updating the child scope's inherited version of editingProfile which does not gets reflected in the one at the parent. But when you do ng-click="backToList()" The function is in the controller and so the $scope.editingProfile refers to the one on the controller (parent) hence that change is reflected and ng-if becomes falsy and it hides the content.

You could solve this my adding one more level in the scope property hierarchy.

angular.module("testApp", []).controller("editCtrl",
    function ($scope){
      $scope.model = {};
      $scope.model.editingProfile = null;
      $scope.edit = function() {
          $scope.model.editingProfile = {
              name: "test"
          };
      }
      $scope.backToList = function() {
          $scope.model.editingProfile = null;
      }
    }    
)

and

<div ng-if="model.editingProfile">Editing {{model.editingProfile.name}}
    <br> <a ng-click="backToList()">click to execute function to go back</a>

    <br/> <a ng-click="model.editingProfile=null">click to set variable to go back(NOT working)</a> 
</div>

Fiddle