我的离子应用程序中的ng-if和ng-show都不起作用 [英] ng-if and ng-show in my Ionic application, neither works

查看:58
本文介绍了我的离子应用程序中的ng-if和ng-show都不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

html代码如下所示:

 < div ng-if =name =='John' > 
< div class =item item-avatar> < img ng-src =john.jpg>< / div>
< / div>
< div ng-if =name =='Margaret'
< div class =item item-avatar> < img ng-src =margaret.jpg>< / div>
< / div>

而不是ng-if,我也尝试过使用ng-show。都没有工作。无论我使用什么,约翰和玛格丽特都在页面上显示。



我之前在同一个HTML文件中初始化的变量'name'为:

 < a class =item item-avatar item-icon-rightng-init =name ='John'href =#/ Page3>< / A> 

点击上面的一行会导致Page3,我需要根据值显示John或Margaret的名称。



语法错了或者是某种东西,因为这可能是非常好的。我是Ionic和AngularJS的新手。 解决方案

我修正了你 plunker - 现在它应该可以正常工作了。

Bug#1:ng-init用于初始化时不要在运行时设置值 - >使用ng-click代替

Bug#2:对所有页面使用相同的控制器,但对于每个页面,新的控制器将会初始化,这会重置'name'属性

我实现了一个setName函数来在rootcope中设置名称并转到page3。在正确的实现中,您应该将名称作为$ stateparam传递给新的状态/页面。但是为此,请查看ui-router文档。

  $ scope.setName = function(name){
console.log(name);
$ rootScope.name = name;
$ state.go('Page3');
};


The html code goes something like this:

<div ng-if="name=='John'">
<div class="item item-avatar"> <img ng-src="john.jpg"></div>
</div>
<div ng-if="name=='Margaret'"
<div class="item item-avatar"> <img ng-src="margaret.jpg"></div>
</div>

Instead of ng-if, I've tried using ng-show as well. Neither worked. Both John as well as Margaret showed on the page no matter which I used. I tried with ng-switch also.

The variable 'name' I initialized earlier on the same HTML file as:

<a class="item item-avatar item-icon-right" ng-init="name = 'John'" href = "#/Page3"></a>

Clicking on the above line leads to Page3 where I need to display either John or Margaret depending on the value of 'name'.

Is the syntax wrong or something, because that could be very well possible. I'm new to Ionic and AngularJS.

解决方案

I fixed you plunker - now it should be working.

Bug #1: ng-init is for initialization not to set values at runtime -> use ng-click instead

Bug #2: You use the same controller for all pages but for each page a new controller will be initialized, which resets the 'name' property

I implemented a setName function to set the name in the rootscope and to go to page3. In a correct implementation you should pass the name as a $stateparam to the new state/page. But for that please have a look at the ui-router documentation.

  $scope.setName = function(name) {
    console.log(name);
    $rootScope.name = name;
    $state.go('Page3');
  };

这篇关于我的离子应用程序中的ng-if和ng-show都不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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