有时我们想让用户可编辑元素某个属性内容,比如自定义数据名称,所以在此实现一个简易的指令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-transclude ng-show="!isEdit"></ng-transclude>
<input type="text" ng-model="tempText" ng-show="isEdit">
<button ng-click="edit()" ng-show="!isEdit">Edit</button>
<button ng-mousedown="save()" ng-show="isEdit">Save</button>
<button ng-mousedown="cancel()" ng-show="isEdit">Cancel</button>
</div>
<body ng-controller="ctrl"> <div ng-model="data" my-editable> {{data}} </div> <!--显示实际Model值用--> <p> {{data}} </p> </body>
当然这个指令存在局限性,比如可以外部获取正则内部做验证用。