问题描述
我发现执行功能,并使用前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.
提琴:
推荐答案
这是因为 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设置范围变量之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!