頁面中有多個span標籤,每個span標籤都綁定了一個雙擊事件,如何在雙擊事件中實現,將被雙頰的span標籤變成input標籤,同時span標籤中的值變成input標籤的value?
迷茫2017-05-15 16:57:25
1.借助html5
的新特性contenteditable
和Angular的指令還是很容易做到的。
2.可以看這個demo
3.具體程式碼如下:
app.js
(function(){
angular.module('MyApp', [])
.controller('MyController', MyController)
.directive('contentEditable', contentEditable);
MyController.$inject = [];
contentEditable.$inject = [];
function MyController(){
var vm = this;
vm.test = 'Hello World!';
}
function contentEditable(){
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
element.html(scope.vm.test);
attrs.$set('contenteditable', false);
ctrl.render = function (value) {
element.html(value);
};
ctrl.$setViewValue(element.html());
element.bind('dblclick', function () {
if (!attrs.contenteditable) {
attrs.$set('contenteditable', true);
element[0].focus();
}
});
element.bind('blur', function () {
attrs.$set('contenteditable', false);
scope.$apply(function () {
ctrl.$setViewValue(element.html());
});
});
element.bind('keydown', function (event) {
var esc_key = event.which === 27,
enter_key = event.which === 13;
if (esc_key || enter_key) {
event.preventDefault();
element[0].blur();
}
});
}
};
}
})();
index.html
<body ng-app="MyApp">
<p class="test-container" ng-controller="MyController as vm">
<p class="test" content-editable ng-model="vm.test"></p>
<hr/>
<p class="test" ng-bind="vm.test"></p>
</p>
</body>
習慣沉默2017-05-15 16:57:25
一般來說都是寫兩個,一個隱藏一個顯示就好:
<span ng-show="!tag.edit" ng-dblclick="tag.edit = true" ng-bing="tag.name"></span>
<input type="text" ng-show="tag.edit" ng-model="tag.name" />
高洛峰2017-05-15 16:57:25
雖然隨便更改需求是不好的……但是我猜你想要的其實只是雙擊之前的input只讀且無邊框,雙擊之後它從只讀變成可編輯、並帶上邊框……
像前面幾位說的那樣加雙擊響應,並在回呼函數中改readonly和style吧。