【发布时间】:2014-06-20 17:50:37
【问题描述】:
我正在尝试使用 angular 指令设置输入 type='checkbox' 的样式,而我的 HTML 布局看起来像这样
<div class="checkbox"><input type="checkbox" ng-model="checked1" /></div>
<div class="checkbox"><input type="checkbox" ng-model="checked2" /></div>
<div class="checkbox"><input type="checkbox" ng-model="checked3" /></div>
到目前为止,我的指令如下所示:
myApp.directive('checkbox', function($parse) {
return {
restrict: "C",
compile: function(elem, attr) {
var model = $parse(attr.ngModel);
return function(scope, elem, attr) {
var toggleValue = function() {
scope.$apply(function(scope) {
model.assign(scope, !model(scope));
});
};
var updateComponent = function(value) {
if(value == true)
elem.addClass('checkbox-active');
else
elem.removeClass('checkbox-active');
};
elem.bind('click', toggleValue);
scope.$watch(model, updateComponent);
};
}
}
});
这个指令的问题是它不是从 div 内的输入中搜索 ng-model,所以如果我有这样的布局,它会起作用
<div class="checkbox" ng-model="checked1"><input type="checkbox" /></div>
我可以在指令的编译中改变一些东西,让它从输入而不是从 div 中读取 ng-model 吗?
【问题讨论】:
标签: javascript html angularjs angularjs-directive