什么是使用功能和使用内联前pression设置范围变量之间的差异 [英] What's the difference between using function and using inline expression to set scope variable

查看:191
本文介绍了什么是使用功能和使用内联前pression设置范围变量之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现执行功能,并使用前pression设置变量,具体地之间的一些差异,似乎纳克-如果未能检测由前所做的更改pression。我不明白为什么。

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.

伪code:

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

该backToList按钮有一个 NG-点击属性,当我写 NG-点击=backToList()执行 $ scope.backToList(),其中 $ scope.editingProfile 设置为false,它的作品不错。但是,当我写 =假editingProfile =使用直接设置变量,在 NG-如果 NG-点击隐藏部分将无法工作。

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.

提琴: http://jsfiddle.net/brfbtbd7/1/

推荐答案

这是因为 NG-如果指令创建一个子范围。因此, NG-IF =editingProfile编辑配置文件父对象,该对象被继承到创建的子范围由NG-IF。这就是被显示@ 编辑{{editingProfile.name}}< BR> 。当你做 NG-点击=editingProfile = FALSE你实际上是在更新子作用域继承的 editingProfile 的版本,不被反映在一个在母体。但是,当你做 NG-点击=backToList()的功能是在控制器等等 $ scope.editingProfile 指控制器(父),因此该变化反映和一个NG-如果变成falsy和它隐藏的内容。

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.

您可以解决了scope属性层次结构中此我再增加一个等级。

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;
      }
    }    
)

<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

这篇关于什么是使用功能和使用内联前pression设置范围变量之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆