angularJS内联编辑器,用于多个“字段”

时间:2013-05-07 01:18:15

标签: javascript angularjs javascript-framework

以下代码片段使我能够编辑页面上的元素,但是,单击P标签,所有其他代码也会变为内联编辑器模式。如何重新编写此脚本,以便只启用单击P标记的编辑器?

JS代码:

function Profile($scope) {
  $scope.person = {
    name : "Test Name",
    company : "Test",
    role : "Test Role"
  };

}

function Editor($scope) {
  $scope.editorEnabled = false;
  $scope.enableEditor = function() {
    $scope.editorEnabled = true;
    $scope.name = $scope.person.name;
    $scope.company = $scope.person.company;
    $scope.role = $scope.person.role;
  },

  $scope.disableEditor = function() {
    $scope.editorEnabled = false;
  },

  $scope.save = function() {
    $scope.person.name = $scope.name; //var = input.value
    $scope.person.company = $scope.company;
    $scope.person.role = $scope.role;
    $scope.disableEditor();
  }
}

HTML:

<div ng-controller="Profile">
    <div ng-controller="Editor">
        <h1 class="center" ng:hide="editorEnabled" ng:click="enableEditor()">{{person.name}}</h1>
        <span ng:show="editorEnabled">
            <form class="form-inline">
                <input type="text" size="30" name="name" ng:required ng-model="name">
                <button class="btn btn-success"  ng:click="save()">Ok</button>
                <button class="btn btn-warning" ng:click="disableEditor()">Cancel</button>
            </form>
        </span>
        <h5 class="center" ng:hide="editorEnabled" ng:click="enableEditor()">{{person.role}} @ {{person.company}}</h5>
        <span ng:show="editorEnabled">
            <form class="form-inline">
                <input type="text" size="30" name="role" ng:required ng-model="role"> @ <input type="text" size="30" name="company" ng:required ng-model="company">
                <button class="btn btn-success"  ng:click="save()">Ok</button>
                <button class="btn btn-warning" ng:click="disableEditor()">Cancel</button>
            </form>
        </span>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

我最有可能接近它的方法是在$scope中引入新字段,以识别哪个字段是可编辑的。然后,您的ngShow指令将包含expression,其中包含以下内容:

<span ng:show="editable == 'company'">

您的ngClick指令看起来像这样:

<h1 ng:click="editor = 'company'">

您的取消按钮会将此设置为null,您的启用/禁用编辑器功能将会消失。请记住这一切都是我的头脑,希望它指出你正确的方向。如果我有机会,我会改进这个答案。