如何在Angular中修改指令模板类名?

时间:2015-10-20 03:33:58

标签: angularjs angularjs-directive glyphicons

这是jsfiddle
HTML:

#container { display: flex; }


JS:

<div ng-app="app">
    <my-checkbox text="apple" status=true></my-checkbox>
    <my-checkbox text="pineapple" status=false></my-checkbox>
    <my-checkbox text="peach" status=true></my-checkbox>
</div>

点击图标后图标不会改变。我做错了什么?有人帮忙吗?
干杯!

1 个答案:

答案 0 :(得分:1)

对于初学者,如果要更改属性值,请使用attr.$set,例如

ele.on('click', function() { // seriously, why does everyone use bind?
    attr.$set('status', !attr.status);
});

其次,您应该观察status属性以更新作用域icon以及手动触发由DOM事件引起的摘要(如click),而不是这样做

var iconChecked = "glyphicon-ok-sign";
var iconUnChecked = "glyphicon-remove-sign";

attr.$observe('status', function(status) {
    if (typeof status === 'string') {
        status = scope.$eval(status);
        attr.$set('status', status);
    }
    scope.icon = status ? iconChecked : iconUnChecked;
});

scope.name = attr.text;
ele.on("click", function() {
    attr.$set('status', !attr.status);
    scope.$apply();
});

http://jsfiddle.net/tL9hfmpo/5/