Dynamic name in angularjs - using ng-attr-title

How can I get a dynamic title in angularJS.I know to use ng-attr-title as below

 <div ng-app="myApp" ng-controller="ctrl"> <div ng-attr-title="{{title}}">Hover me</div> </div> 

and controller

 var app = angular.module('myApp', []); function ctrl($scope){ $scope.title = "I 'ma tooltip!"; } 

Here is JSfiddle and its work. What I'm trying to do is to have two different headers, one at power-up and the other off, so I want to solve a variable that goes into ng-attr-title at runtime, as follows.

 <div ng-app="myApp" ng-controller="ctrl"> <div ng-attr-title="{{message}}">Hover me</div> </div> 

and controller

 var app = angular.module('myApp', []); function ctrl($scope){ $scope.Enabledtitle = "U can click me"; $scope.Disabledtitle = "U cannot click me"; $scope.message="Enabledtitle"; } 

So, when I am, I should get a tooltip "U can click me". SO that I get the flexibility to switch between tooltip messages by simply updating the message scope variable

Here is a JSfiddle where I tried the dynamic name and get "Enabledtitle" as a hint instead of "U can click on me."

How can I tell angular to parse {{Enabledtitle}} and evaluate its value.

+5
source share
3 answers

To access a property with the name of a variable, you will need to use parenthesis . Thus, the title attribute becomes ng-attr-title="{{this[message]}} :

 var app = angular.module('myApp', []); function ctrl($scope) { $scope.Enabledtitle = "U can click me"; $scope.Disabledtitle = "U cannot click me"; $scope.message = "Enabledtitle"; } 
 <script src="http://code.angularjs.org/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="ctrl"> <div ng-attr-title="{{this[message]}}">Hover me</div> </div> 

In your case, this points to the current $scope object, and you read its property using the dynamic key message .

Demo: http://jsfiddle.net/oetd3bvy/2/

+4
source

In the controller:

 $scope.getMessage() { return isEnabled ? "You can click me" : "You can't click me"; } 

in view:

 <div title="{{ getMessage() }}">...</div> 

Or, every time the code changes the value of the isEnabled flag, also change the message.

+5
source

do

 $scope.message=$scope.Enabledtitle; 

instead

 $scope.message="Enabledtitle"; 
+2
source

Source: https://habr.com/ru/post/1234764/


All Articles