node.js和angularjs noob在这里,所以要温柔:)。
我在我的堆栈中使用meanjs。
我已使用模板替换设置了单击编辑功能以添加输入字段,但我无法确定如何在模板更改时自动将焦点设置到输入字段。我的指令如下:
angular.module('core').directive("clickToEdit", function(){
var editorTemplate = '<div class="click-to-edit">' +
'<div data-ng-click="enableEditor()" data-ng-hide="view.editorEnabled">' +
'{{value}} ' +
'</div>' +
'<div data-ng-show="view.editorEnabled">' +
'<input data-ng-model="view.editableValue" data-ng-blur="disableEditor()" />' +
'</div>' +
'</div>';
return {
restrict: "A",
replace: true,
template: editorTemplate,
scope: {
value: "=clickToEdit",
},
controller: function($scope) {
$scope.view = {
editableValue: $scope.value,
editorEnabled: false
};
$scope.enableEditor = function() {
$scope.view.editorEnabled = true;
$scope.view.editableValue = $scope.value;
};
$scope.disableEditor = function() {
$scope.view.editorEnabled = false;
};
$scope.save = function() {
$scope.value = $scope.view.editableValue;
$scope.disableEditor();
};
}
};
});
答案 0 :(得分:0)
你可以在简单的JS中使用focus()函数。一招:我把它包装在$ timeout中让模板渲染。
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-app="plunker" ng-controller="MainCtrl">
<div click-to-edit="value"></div>
</body>
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.value="Click to edit";
}]).directive("clickToEdit", function(){
var editorTemplate = '<div class="click-to-edit">' +
'<div data-ng-click="enableEditor()" data-ng-hide="view.editorEnabled">' +
'{{value}} ' +
'</div>' +
'<div data-ng-show="view.editorEnabled">' +
'<input data-ng-model="view.editableValue" data-ng-blur="disableEditor()" />' +
'</div>' +
'</div>';
return {
restrict: "A",
replace: true,
template: editorTemplate,
scope: {
value: "=clickToEdit",
},
controller: function($scope, $element, $timeout) {
$scope.view = {
editableValue: $scope.value,
editorEnabled: false
};
$scope.enableEditor = function() {
$scope.view.editorEnabled = true;
$scope.view.editableValue = $scope.value;
var input = $element.find('input');
$timeout(function() {
input[0].focus();
});
};
$scope.disableEditor = function() {
$scope.view.editorEnabled = false;
};
$scope.save = function() {
$scope.value = $scope.view.editableValue;
$scope.disableEditor();
};
}
};
});
</script>
</html>
&#13;