我正在尝试编写一条指令,该指令将对元素进行简单的就地编辑。到目前为止,这是我的代码:
directive('clickEdit', function() {
return {
restrict: 'A',
template: '<span ng-show="inEdit"><input ng-model="editModel"/></span>' +
'<span ng-show="!inEdit" ng-click="edit()">{{ editModel }}</span>',
scope: {
editModel: "=",
inEdit: "@"
},
link: function(scope, element, attr) {
scope.inEdit = false;
var savedValue = scope.editModel;
var input = element.find('input');
input.bind('keyup', function(e) {
if ( e.keyCode === 13 ) {
scope.save();
} else if ( e.keyCode === 27 ) {
scope.cancel();
}
});
scope.edit = function() {
scope.inEdit = true;
setTimeout(function(){
input[0].focus();
input[0].select();
}, 0);
};
scope.save = function() {
scope.inEdit = false;
};
scope.cancel = function() {
scope.inEdit = false;
scope.editModel = savedValue;
};
}
}
})
scope.edit函数将inEdit设置为true,并且效果很好-它隐藏了文本并显示了输入标签。但是,将scope.inEdit设置为false的scope.save函数根本不起作用。它不会隐藏输入标签并显示文本。
为什么?
您是scope.save()
从对事件做出反应的事件处理程序调用的keyup
。但是,AngularJS框架不会调用该事件处理程序。AngularJS仅在认为可能已发生更改以减轻工作量时才扫描模型的更改(到目前为止,AngularJS进行脏检查是计算密集型的)。
因此,您必须利用该scope.$apply
功能使AngularJS知道您正在对范围进行更改。将scope.save
函数更改为此,它将起作用:
scope.save = function(){
scope.$apply(function(){
scope.inEdit = false;
});
});
而且似乎实际上没有必要将此save
函数绑定到范围变量。因此,您可能想改为定义“常规”函数或仅将代码集成到事件处理程序中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句