为什么更改范围在 ng-if 中不起作用,而是通过函数调用 - AngularJS
Why changing a scope won't work inside a ng-if but via function call - AngularJS
以下是我在其中切换 hideQA
值的代码片段,该值在两种情况下都在正确更改,但如果我正在执行 -
则没有正确隐藏 div
`<button ng-click="hideQA = !hideQA">Reset</button>`
但是如果我从一个方法更改值,它工作正常,比如 -
`<button ng-click="resetForm()">Reset</button>`
谁能解释一下这背后的原因?
这是因为范围之间的继承限制。
为了没有问题,您必须使用点符号。
查看 plunkr : http://plnkr.co/edit/ES9qTl7nsmGGOJnE0H8u?p=preview
有关点符号的更多说明,请参阅文章
你的代码看起来像点符号:
<button ng-click="a.hideQA = !a.hideQA">Reset</button>
$scope.a = {hideQA:false};
$scope.a.hideQA = true;
ng-if
有自己的 $scope
,当元素被移除时,$scope
也会被移除。所以你必须使用 $parent
来引用父范围
<button ng-click="$parent.hideQA = !hideQA">Reset</button>
另一种选择是使用 ng-show
<div class="message" ng-show="hideQA !== false">
This is div two !!!
<button ng-click="hideQA = !hideQA">Reset</button>
</div>
上面给出的答案已经解决了这个问题。这是我的工作 plunkr link:http://plnkr.co/edit/ZdL441bBmQToGZn4gfQt?p=preview。我还要说点别的:
当你使用 ng-if
时,它会创建自己的作用域,来自 angularjs 官方文档:
The scope created within ngIf inherits from its parent scope using prototypal inheritance.
简而言之,当从它的父作用域引用值时,只复制主要类型的值(如 string
、integer
、boolean
等),但不会值的引用(或 pointer
)。这意味着它是单向参考而不是双向参考。因此,为了作为双向使用,最佳做法是始终使用 javascript object {attr: value}
。这就是为什么 .
被推荐。
这是一篇非常好的文章,值得花 20 分钟准备好范围 https://github.com/angular/angular.js/wiki/Understanding-Scopes
希望对您有所帮助:)
以下是我在其中切换 hideQA
值的代码片段,该值在两种情况下都在正确更改,但如果我正在执行 -
`<button ng-click="hideQA = !hideQA">Reset</button>`
但是如果我从一个方法更改值,它工作正常,比如 -
`<button ng-click="resetForm()">Reset</button>`
谁能解释一下这背后的原因?
这是因为范围之间的继承限制。
为了没有问题,您必须使用点符号。
查看 plunkr : http://plnkr.co/edit/ES9qTl7nsmGGOJnE0H8u?p=preview
有关点符号的更多说明,请参阅文章
你的代码看起来像点符号:
<button ng-click="a.hideQA = !a.hideQA">Reset</button>
$scope.a = {hideQA:false};
$scope.a.hideQA = true;
ng-if
有自己的 $scope
,当元素被移除时,$scope
也会被移除。所以你必须使用 $parent
<button ng-click="$parent.hideQA = !hideQA">Reset</button>
另一种选择是使用 ng-show
<div class="message" ng-show="hideQA !== false">
This is div two !!!
<button ng-click="hideQA = !hideQA">Reset</button>
</div>
上面给出的答案已经解决了这个问题。这是我的工作 plunkr link:http://plnkr.co/edit/ZdL441bBmQToGZn4gfQt?p=preview。我还要说点别的:
当你使用 ng-if
时,它会创建自己的作用域,来自 angularjs 官方文档:
The scope created within ngIf inherits from its parent scope using prototypal inheritance.
简而言之,当从它的父作用域引用值时,只复制主要类型的值(如 string
、integer
、boolean
等),但不会值的引用(或 pointer
)。这意味着它是单向参考而不是双向参考。因此,为了作为双向使用,最佳做法是始终使用 javascript object {attr: value}
。这就是为什么 .
被推荐。
这是一篇非常好的文章,值得花 20 分钟准备好范围 https://github.com/angular/angular.js/wiki/Understanding-Scopes
希望对您有所帮助:)