jeudi 19 février 2015

Changing bootstrap dropdown button's text using an angular.js directive


I am working on an application and before getting too deep I wanted to do a test. I have a button created using Bootstrap. I have the Bootstrap angular directives installed. I wanted to change the text of the button based upon the selection the user makes on that button. Here is my code:


the Index.html file:



<!doctype html>
<html ng-app="SchedgMeApp">
<head>
<!--<script src="js/angular.min.js"></script>-->
<script src="http://ift.tt/1jZK0bN"></script>
<script src="js/ui-bootstrap-custom-tpls-0.12.0.js"></script>
<script src="http://ift.tt/1yCEpkO"></script>
<script src="js/app.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">

</head>
<body>

<div ng-controller="DropdownCtrl">
<!-- Single button -->
<div class="btn-group" dropdown is-open="status.isopen">
<button type="button" class="btn btn-primary dropdown-toggle" dropdown-toggle ng-disabled="disabled">
<span class="selection">{{ selectedAction.name }}</selection> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li ng-repeat="action in actions">
<a ng-click="setAction(action)">{{ action.name }}</a>
</li>
</ul>
</div>
</div>
</body>
</html>


The app.js file:



var app = angular.module('SchedgMeApp',['ui.bootstrap']);
angular.module('SchedgMeApp').controller('DropdownCtrl', function($scope, $log){
$scope.status = {
isopen: false
};

$scope.toggled = function(open) {
$log.log('Dropdown is now: ', open);
};

$scope.toggleDropdown = function($event) {
$event.preventDefault();
$event.stopProagation();
$scope.status.isopen = !$scope.status.isopen;
};

$scope.actions = [
{id: 'calbert', name: 'Chris Albert'},
{id: 'mmahony', name: 'Mike Mahony'},
{id: 'ctfletcher', name: 'CT Fletcher'},
{id: 'rjohnson', name: 'Rob Johnson'}
];

$scope.setAction = function(action) {
$scope.selectedAction = action;
};

});


This works, but the code to change the text on the button is in the controller and I would prefer it in a directive because I would like to be able to populate the data for every dropdown button in my site this way and have every dropdown button in my site respond in the same manner. So here are my questions:



  1. How do I do this through an angular directive?

  2. How can I set a default value on initial load? <-- solved...see comment

  3. How can I make this so that I have data for all the buttons in my JS, but can pick which data to use on a particular button? I assume a model? <--solved...see comment





Aucun commentaire:

Enregistrer un commentaire