如何在ng-if AngularJS中使用JavaScript? [英] How to use JavaScript inside ng-if AngularJS?

查看:52
本文介绍了如何在ng-if AngularJS中使用JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 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

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


如果表达式是假的那么该元素将从DOM
树中删除。如果它是真实的,则编译元素的副本将添加到
DOM树中。

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.

是否可以只使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆