在指令中设置文本框的焦点

时间:2015-12-04 16:37:17

标签: angularjs

我在这里尝试使用内联编辑指令表单:http://icelab.com.au/articles/levelling-up-with-angularjs-building-a-reusable-click-to-edit-directive/

我想知道如何在单击要编辑的文本时在文本框中设置光标。

以下是对模板进行一些细微更改的指令:

.directive("clickToEdit", function() {
    var editorTemplate = '<div class="click-to-edit">' +
        '<div ng-hide="view.editorEnabled" ng-click="enableEditor()">' +
            '{{value}} ' +
        '</div>' +
        '<div ng-show="view.editorEnabled">' +
            '<input ng-model="view.editableValue" ng-blur="save()">' +
        '</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();
            };
        }
    };
});

1 个答案:

答案 0 :(得分:0)

您需要添加如下链接功能:

link : function(scope, ele, attrs) {
      scope.$watch('view.editorEnabled', function(n, o) {
          if(n) ele.find('input')[0].focus();

      })
}
相关问题