In my project, I am facing an issue with a directive nested within an ng-repeat. The ng-repeat item is passed to the directive and I am trying to generate a directive template or templateUrl with dynamic elements based on a key/value in the item. Specifically, I want to make a button red if the item number is greater than 50, otherwise blue.
I suspect that I might not be using the right approach to solve this problem. My aim is to modify Bootstrap tags based on certain conditions. For example, I would like to apply the logic:
if item.number > 50:
class="btn btn-danger"
else:
class="btn btn-success"
If possible, I prefer using templateUrl as I need the button to trigger a bootstrap modal which might be difficult to incorporate in the basic template option. Passing individual scope variables to the template seems like a cleaner solution.
You can check out this JSFiddle link for more context on the problem.
Here is the HTML snippet:
<div ng-controller="TableCtrl">
<table>
<thead>
<tr>
<th>#</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in buttons">
<td>{{item.id}}</td>
<td new-button item='item'></td>
</tr>
</tbody>
</table>
</div>
And here is the corresponding JavaScript code:
var myApp = angular.module('myApp', []);
function TableCtrl($scope) {
$scope.buttons = {
button1: {
id: 1,
number: '10',
},
button2: {
id: 2,
munber: '85',
}
};
};
myApp.directive('newButton', function() {
return {
restrict: 'A',
replace: true,
scope: {
item: '=',
},
link: function(elem, attrs, scope) {
// This is most likely not the right location for this
/*if (item.number > 50) {
button.color = red
}, else {
button.color = blue
}; */
},
template: '<td><button type="button">{{button.color}}</button></td>'
}
});