有时我们想让用户可编辑元素某个属性内容,比如自定义数据名称,所以在此实现一个简易的指令my-editable
先看效果吧:
指令代码:
.directive('myEditable',function ($timeout) {
return {
restrict: 'A',require: '?ngModel',templateUrl: "./t.html",transclude: true,link: function (scope,element,attrs,ngModel) {
if (!ngModel) {
return;
}
scope.isEdit = false;
//获取内部输入框的controller
var tempInputCtrl = element.find("input").controller("ngModel");
tempInputCtrl.$parsers.push(function (value) {
//做输入验证,此处以不超过10位为例
var return_value = value;
if (value.length > 10) {
console.log("over 10");
return_value = value.slice(0,10);
}
tempInputCtrl.$setViewValue(return_value);
tempInputCtrl.$render();
return return_value;
});
scope.edit = function () {
scope.isEdit = true;
scope.tempText = ngModel.$modelValue;
// 输入框获取焦点
$timeout(function () {
element.find("input")[0].focus();
})
}
scope.save = function () {
var html = scope.tempText;
ngModel.$setViewValue(html);
scope.isEdit = false;
}
scope.cancel = function () {
scope.isEdit = false;
}
ngModel.$render = function () {
scope.tempText = ngModel.$viewValue;
};
element.find("input").on("blur",function () {
console.log("input blur");
scope.isEdit = false;
scope.$apply();
})
}
};
})
t.html指令模板代码:
<div>
<ng@H_404_160@-transclude ng@H_404_160@-show="!isEdit"></ng@H_404_160@-transclude>
<input type="text" ng@H_404_160@-model="tempText" ng@H_404_160@-show="isEdit">
<button ng@H_404_160@-click="edit()" ng@H_404_160@-show="!isEdit">Edit</button>
<button ng@H_404_160@-mousedown="save()" ng@H_404_160@-show="isEdit">Save</button>
<button ng@H_404_160@-mousedown="cancel()" ng@H_404_160@-show="isEdit">Cancel</button>
</div>
<body @H_404_160@ng-controller="ctrl"> <div @H_404_160@ng-model="data" @H_404_160@my-editable> {{data}} </div> <!--显示实际Model值用--> <p> {{data}} </p> </body>
当然这个指令存在局限性,比如可以外部获取正则内部做验证用。
原文链接:https://www.f2er.com/angularjs/147199.html