javascript AngularJS $watch 变量并重新评估 ng-class 表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22787848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS $watch variable and reevaluate ng-class expression
提问by Martin Broder
I'm trying to implement a bookmark-like function into my app and have to watch a variable, which stores all the bookmarked ID's. Based on that variable I have to tell ng-class
to reevaluate it's function expression so the class bookmarked
get's added or not.
我正在尝试在我的应用程序中实现一个类似书签的功能,并且必须监视一个变量,该变量存储所有带书签的 ID。基于该变量,我必须告诉ng-class
重新评估它的函数表达式,以便bookmarked
添加或不添加该类。
How do I tell ng-class
to run again when the variable $scope.Bookmarks
changes?
ng-class
当变量$scope.Bookmarks
发生变化时,我如何告诉再次运行?
<a ng-repeat="event in events"
ng-class="isBookmarked(event.id)"
class="icon__bookmark"></a>
回答by alexsanford1
If the bookmark ID's are being changed in code handled by angular (such as in a controller, a directive, a service, an $http callback, etc.) then you don't need to do anything at all. Angular will automatically re-evaluate isBookmarked(event.id)
when it needs to in order to ensure that the UI is always up to date.
如果书签 ID 在 angular 处理的代码中被更改(例如在控制器、指令、服务、$http 回调等中),那么您根本不需要做任何事情。Angular 会isBookmarked(event.id)
在需要时自动重新评估,以确保 UI 始终是最新的。
If, for some reason, the updates mustbe done outside of code that is handled by angular (such as in an external library), then you can manually force angular to update. However, it is highly recommendedto just ensure that the code is handled by angular. You can usually do this, but it depends on the situation.
如果由于某种原因,更新必须在 angular 处理的代码之外完成(例如在外部库中),那么您可以手动强制 angular 更新。但是,强烈建议仅确保代码由 angular 处理。您通常可以这样做,但这取决于具体情况。
If you need to force it, then use $scope.$apply
as follows:
如果需要强制,那么使用$scope.$apply
如下:
$scope.$apply(function() {
// Write code here to update bookmark ID's
});
回答by Brocco
Assuming the class you want to add a class named "bookmarked" to the anchor tag and that isBookmarked returns a boolean, use this (fiddle):
假设您想将名为“bookmarked”的类添加到锚标记并且 isBookmarked 返回一个布尔值的类,请使用此(fiddle):
<a ng-repeat="event in events"
ng-class="{bookmarked: isBookmarked(event.id)}"
class="icon__bookmark">{{event.name}}</a>
You should not have to call $apply if the bookmarks array is within the controller, please see the fiddle I provided.
如果书签数组在控制器内,则不必调用 $apply,请参阅我提供的小提琴。
回答by Piacenti
Try $route.reload()
. It works very well for directives that are only evaluated once when the page is loaded (like the type that uses JQuery to do DOM manipulation).
试试$route.reload()
。它非常适用于在页面加载时仅评估一次的指令(例如使用 JQuery 进行 DOM 操作的类型)。