简体   繁体   中英

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. Here is a snippet of it.

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

userInformation.value return 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. 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). 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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