问题描述
我试图在 ng-if
中使用 JavaScript
表达式。但是,它没有做任何事情。它总是返回 false
。
I was trying to use a JavaScript
expression with ng-if
. However, it didn't do anything. It allways returns false
.
我尝试过的是:
ng-if =localStorage.getItem('grid-layout')=='list'
(如果为true) ,show div)
div
不会渲染,因为它总是返回 false
。网格布局值保存在 localStorage
中。这不是问题。
The div
doens't render, because it allways returns false
. The grid-layout value is saved in the localStorage
. This is not the issue.
我检查了网站上的文档。 Angular
说明以下关于 ng-if
I checked the documentation on the website. Angular
says the following about ng-if
https://docs.angularjs.org/api/ng/directive/ngIf
是否可以只使用 JavaScript
里面 ng-if
?如果没有,我怎样才能实现我想做的事情?
Is it possible to use just JavaScript
inside ng-if
? If not, how can i archieve what i was trying to do?
推荐答案
你可以在ng-if中使用Javascript表达式,但您只能访问当前模板的 $ scope
中的属性。
You can use Javascript expression inside an ng-if, but you are only able to access properties that are in the $scope
of the current template.
除非你专门将它添加到 localStorage 不太可能。 > $ scope object。
It's unlikely that localStorage
would be available to you unless you had specifically added it to the $scope
object.
一种方法是在控制器中写一个附加到$ scope的函数:
One approach would be to write a function attached to the $scope in your controller:
//in controller JS
$scope.checkLocalStorage = function() {
return localStorage.getItem('grid-layout') == 'list';
}
//In template
<div ng-if="checkLocalStorage()"></div>
这篇关于如何在ng-if AngularJS中使用JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!