问题
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.
回答1:
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/
回答2:
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.
回答3:
do
$scope.message=$scope.Enabledtitle;
instead of
$scope.message="Enabledtitle";
来源:https://stackoverflow.com/questions/33407974/dynamic-title-in-angularjs-using-ng-attr-title