AngularJS實現一個HTML元素內容可編輯指令
阿新 • • 發佈:2018-12-31
有時我們想讓使用者可編輯元素某個屬性內容,比如自定義資料名稱,所以在此實現一個簡易的指令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>
HTML程式碼:
<body ng-controller="ctrl">
<div ng-model="data" my-editable>
{{data}}
</div>
<!--顯示實際Model值用-->
<p>
{{data}}
</p>
</body>
當然這個指令存在侷限性,比如可以外部獲取正則內部做驗證用。