gpt4 book ai didi

javascript - 如何在 ng-if AngularJS 中使用 JavaScript?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:40:46 26 4
gpt4 key购买 nike

我试图将 JavaScript 表达式与 ng-if 结合使用。但是,它没有做任何事情。它总是返回 false

我尝试的是:

ng-if="localStorage.getItem('grid-layout') == 'list' (如果为真,显示 div)

div 不呈现,因为它总是返回 false。网格布局值保存在 localStorage 中。这不是问题。

我检查了网站上的文档。 Angular 说明了以下关于 ng-if

的内容

https://docs.angularjs.org/api/ng/directive/ngIf

If the expression is falsy then the element is removed from the DOM tree. If it is truthy a copy of the compiled element is added to the DOM tree.

是否可以在 ng-if 中只使用 JavaScript?如果没有,我怎样才能实现我想要做的事情?

最佳答案

您可以在 ng-if 中使用 Javascript 表达式,但您只能访问当前模板的 $scope 中的属性。

localStorage 不太可能对您可用,除非您专门将它添加到 $scope 对象。

一种方法是在 Controller 中编写一个附加到 $scope 的函数:

//in controller JS
$scope.checkLocalStorage = function() {
return localStorage.getItem('grid-layout') == 'list';
}

//In template
<div ng-if="checkLocalStorage()"></div>

关于javascript - 如何在 ng-if AngularJS 中使用 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44281766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com