仅更改一个范围以在ng-repeat

时间:2016-08-12 08:02:08

标签: javascript angularjs

我有一个简单的应用程序,显示任务。我想双击任务进行编辑,因此我希望将其从<span>更改为<input type="text" />。这是我的代码:

<li ng-repeat="task in tasks">
    <input type="checkbox" ng-checked="task.done" ng-click="taskDone(task.id, !task.done)"/>
    <span ng-dblclick="editTask()" ng-if="!editable">{{::task.task}}</span>
    <input type="text" ng-if="editable" value="{{task.task}}" />
</li>

但是,当我双击任务时,每<span>次更改为<input type="text" />

enter image description here

这是生成HTML代码的指令:

export const tasksList = function() {
    return {
        restrict: 'E',
        scope: {
            tasks: "="
        },
        templateUrl: '../dist/views/tasksList.html',
        link: function(scope, element, attrs) {
            scope.$watchCollection('tasks', function(tasks) {
                scope.updateTasks();
            });
        },
        controller: function($scope) {
            const self = this;
            $scope.editable = false;
            $scope.editTask = function() {
                $scope.editable = true;
            };
            $scope.updateTasks = function() {
                self.tasks = $scope.tasks;
            };
            $scope.taskDone = function(id, taskDone) {
                $scope.tasks[id].done = taskDone;
            };
        },
        controllerAs: "$ctrl"
    };
};

如何只将<span>更改为<input type="text" />

1 个答案:

答案 0 :(得分:3)

尝试在任务上放置editable标志,而不是范围。

<li ng-repeat="task in tasks">
    <input type="checkbox" ng-checked="task.done" ng-click="taskDone(task.id, !task.done)"/>
    <span ng-dblclick="editTask(task)" ng-if="!task.editable">{{::task.task}}</span>
    <input type="text" ng-if="task.editable" value="{{task.task}}" />
</li>

...
$scope.editTask = function(task) {
     task.editable = true;
 };
...