Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Title in angularjs - using ng-attr-title

Tags:

angularjs

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.

like image 420
Divya MV Avatar asked Oct 29 '15 07:10

Divya MV


3 Answers

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/

like image 106
dfsq Avatar answered Nov 14 '22 20:11

dfsq


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.

like image 8
JB Nizet Avatar answered Nov 14 '22 22:11

JB Nizet


do

$scope.message=$scope.Enabledtitle;  

instead of

$scope.message="Enabledtitle";
like image 2
Disha Avatar answered Nov 14 '22 22:11

Disha