【发布时间】:2016-04-20 21:03:56
【问题描述】:
我有一个嵌套在 ng-repeat 中的指令。 ng-repeat 项被传递给指令。我正在尝试根据传递给指令的项目中的键/值生成指令模板(用于测试)或带有可变元素的 templateUrl。本质上,如果 item.number > 50 使按钮变为红色,否则将其变为蓝色。
我可能使用了错误的工具来解决问题。目标是使用类似的东西来更改 Bootstrap 标签。比如逻辑:
if item.number > 50:
class="btn btn-danger"
else:
class="btn btn-success"
如果可能的话,我会尝试使用 templateUrl: 来解决这个问题,因为我想要启动引导模式的按钮,这很适合基本模板选项。传递模板的单个作用域变量要干净得多。
这是试图描述问题的JSFiddle。
html
<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>
app.js
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>'
}
});
【问题讨论】:
标签: javascript angularjs twitter-bootstrap