我有以下指令:
mod.directive('mdCheckbox', function(){
var link = function(scope, element, attr, ngModel){
var inp = element.find('input');
scope.$watch(function(){
return ngModel.$viewValue;
}, function(newVal){
console.log('newVal: ' + newVal);
if(newVal){
inp.attr('checked', 'checked');
}else{
inp.removeAttr('checked');
}
});
scope.clickT = function(evt){
// ** why the need for stopPropagation ?
evt.stopPropagation();
console.log('click called');
if(inp.is(':checked')){
ngModel.$setViewValue(false);
console.log('set to false');
}else{
ngModel.$setViewValue(true);
console.log('set to true');
}
};
};
var directive = {
restrict: 'EA',
require: 'ngModel',
scope: {
text: '@mdText'
},
template: '<div ng-click="clickT($event)" class="checkbox"><input type="checkbox"/>' +
'<span>{{text}}</span></div>',
replace: true,
link: link
};
return directive;
});
和html:
<md-checkbox md-text="Is Awesome" ng-model="user.isAwesome"></md-checkbox>
现在,clickT处理程序被调用了两次,我必须停止对其进行传播。但是我不清楚为什么会这样。第二个问题是,即使这看起来像是可行的,但在单击两次后,它就停止了工作-该值不再更改true / false。
这是测试用的朋克
谢谢。
您不应该手动更改DOM,因为您可以为此使用数据绑定。但我不会对此进行讨论,因为这不是您所提问题的答案。
您示例中的问题是切换“检查/取消选中”复选框的代码。它不是属性,而是属性(可以为true / false,不包含值)。
初始加载后,该checked
属性不会更新该checked
属性。该属性实际上与defaultChecked
属性有关。
更改为:
if (newVal) {
inp.prop('checked', true);
} else {
inp.prop('checked', false);
}
另外,您可以删除stopPropagation调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句