This tip continue the idea from Angular JS - Use ng-model Directive For Creating Custom Form Elements. In that tip we had used the ng-model directive for creating the well-known Bootstrap Vertical Pillscomponent. But, notice that we didn't update the data-bound value. For this we have to use the scope.$apply method, that it is used to push updates into the data model.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="../angular/angular.min.js"></script>
<link href="../bootstrap/css/bootstrap.css" rel="stylesheet"/>
<link href="../bootstrap/css/bootstrap-theme.css" rel="stylesheet"/>
<script type="text/ng-template" id="verticalPillsTemplate">
<ul class="nav nav-pills nav-stacked" role="tablist">
<li role="presentation" class="active"><a href="#">None</a></li>
<li role="presentation" ng-repeat="item in playerslocal">
<a href="#">{{item.name}}</a>
</li>
</ul>
</script>
<script>
angular.module("appModule", [])
.controller("appCtrl", function ($scope) {
$scope.players = [
{ name: 'Nadal, Rafael (ESP)', rank: 1, age: '28', prizemoney: 66149345 },
{ name: 'Djokovic, Novak (SRB)', rank: 2, age: '27', prizemoney: 70704129 },
{ name: 'Federer, Roger (SUI)', rank: 3, age: '33', prizemoney: 84827704 },
{ name: 'Wawrinka, Stan (SUI)', rank: 4, age: '29', prizemoney: 13155060 },
{ name: 'Ferrer, David (ESP)', rank: 5, age: '32', prizemoney: 24034072 },
{ name: 'Tsonga, Jo-Wilfried (FRA)', rank: 11, age: '29', prizemoney: 1708240 },
{ name: 'Simon, Gilles (FRA)', rank: 26, age: '29', prizemoney: 760469 },
{ name: 'Lopez, Feliciano (ESP)', rank: 20, age: '33', prizemoney: 1100579 },
{ name: 'Benneteau, Julien (FRA)', rank: 28, age: '32', prizemoney: 617688 },
{ name: 'Verdasco, Fernando (ESP)', rank: 33, age: '30', prizemoney: 689219 },
{ name: 'Mayer, Leonardo (ARG)', rank: 25, age: '27', prizemoney: 946294 }
];
$scope.selectedPlayer = 'None';
})
.directive("playersPills", function () {
return {
scope: { playerslocal: "=playersattr" },
replace: true,
restrict: 'E',
require: "ngModel",
template: document.querySelector("#verticalPillsTemplate").innerHTML,
link: function (scope, element, attrs, ctrl) {
element.on("click", function (event) {
setSelectedPlayer(event.target.innerText);
scope.$apply(function () {
ctrl.$setViewValue(event.target.innerText);
});
});
var setSelectedPlayer = function (value) {
var lis = element.find("li");
lis.removeClass("active");
for (var i = 0; i < lis.length; i++) {
if (lis.eq(i).text() == value) {
lis.eq(i).addClass("active");
}
}
}
ctrl.$render = function () {
setSelectedPlayer(ctrl.$viewValue || 'None');
}
}
}
});
</script>
</head>
<body>
<div ng-app="appModule" ng-controller="appCtrl">
<div class="well">
Player:
<select ng-model="selectedPlayer">
<option>None</option>
<option ng-repeat="item in players">{{item.name}}</option>
</select>
</div>
<players-pills ng-model="selectedPlayer" playersattr="players"/>
</div>
</body>
</html>
Niciun comentariu:
Trimiteți un comentariu