10

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

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

and the controller is

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

Here is the JSfiddle and its working. What i am trying is to have two different titles one while enabled and another while disabled so i want to decide the variable that goes in to ng-attr-title at runtime as given below.

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

and the controller is

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 hover i should get the tooltip saying "U can click me". SO that i get the flexibility to switch between the tooltip messages just by updating the scope variable message

Here is the JSfiddle where i tried the dynamic title and am getting "Enabledtitle" as tooltip instead of "U can click me".

How can i tell angular to parse {{Enabledtitle}} and gimme its value.

3 Answers 3

14

You will need to use bracket notation to access property with the variable name. So 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 current scope object $scope and you are reading it's property by dynamic key message.

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

Sign up to request clarification or add additional context in comments.

Comments

8

In the controller:

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

in the view:

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

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

2 Comments

Can we also pass a variable to getMessage(), for example, if the div is defined within an ng-repeat element?
@user1438038 yes, you can.
2

do

$scope.message=$scope.Enabledtitle;  

instead of

$scope.message="Enabledtitle";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.