简体   繁体   English

如何使用AngularJS显示按钮或锚标记值?

[英]How to display button or anchor tag value with AngularJS?

I am trying to display a button or anchor tag value based on what my angular variable return as true or false. 我试图根据我的角度变量返回的值显示为true或false来显示按钮或锚标签值。 Here is a snippet of it. 这是它的一个片段。

<a href="#" id="verify">{{userInformation.value}}</a>

userInformation.value return true/false. userInformation.value返回true / false。 Now what I want is to display particular value for the button element based on what the angular returns. 现在,我要根据角度返回值显示按钮元素的特定值。

Something like : 就像是 :

<a href="#" id="verify">{{userInformation.value === true ? displaysomething : displaysomethingelse}}</a>

Any suggestions would be of great help. 任何建议都会有很大帮助。

你可以试试这个

<a href="#" id="verify">{{userInformation.value ? 'Hello': 'Hi'}}</a>

Instead of doing ng-if, consider creating a function in the controller that would decide what to display for you. 可以考虑在控制器中创建一个函数来决定要显示的内容,而不是执行ng-if。 This would allow you to keep the business logic in your controller and out of your template and you could unit test (which is generally a good idea). 这将使您可以将业务逻辑保留在控制器中并且不包含在模板中,并且可以进行单元测试(通常是个好主意)。 Also, it would be open for more than just two conditions for value (eg if you had to check more than just true/false). 同样,它会开放两个以上的价值条件(例如,如果您必须检查的不仅仅是true / false)。 Example here: 这里的例子:

 angular.module('myApp', []) .controller('MainController', function() { // initial user info object this.userInformation = { value: true }; // swap values for demo purpose this.swapValue = function(obj) { obj.value = !obj.value; }; // logic for display lives here this.getUserInfoDisplay = function(userInfo) { if (userInfo.value) { return 'Display something'; } else { return 'Display something else'; } }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!-- Controller as syntax --> <div ng-app="myApp" ng-controller="MainController as ctrl"> <a href="#">{{ctrl.getUserInfoDisplay(ctrl.userInformation)}}</a> <br /> <button ng-click="ctrl.swapValue(ctrl.userInformation)"> Swap Value </button> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM