angularjsangularjs-ng-repeatangularjs-ng-disabled

how to write function to target specific variable for ng disable that inside ng repeat?


I'm trying to build todo list app in angular. When you add new item, it will add to input box(by default, i set it to disabled) inside the table and also add Edit link next to that input. Once i click on the Edit, the input box will enable. ( i got it working with this code (Edit).

My question is how to replace ng-click="editable=!editable" with ng-click="edit()". I tried to write that Edit function, but i can't get it to work. Please help. My code on jsfiddle

Thanks so much.

<body ng-app="shoppingList">
<div  ng-controller="mainController">
    <h1>My Shopping List</h1>
    <form class="form-inline" ng-submit="addItem()">
        <div class="form-group">
        <input type="text" ng-model="newItem">
        </div>
        <input type="submit" value="Add">   
    </form>
    <div>
        <table>
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Edit</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in items track by $index">
                    <td><input ng-disabled="!editable" type="text" value="{{item}}"></td>
                    <td ng-click="editable=!editable">Edit</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>  
<script>
(function(){
    var app = angular.module('shoppingList',[]);
    app.controller('mainController',function($scope){
        $scope.items=[];
        $scope.addItem = function(){
            $scope.items.push($scope.newItem);
        };

    $scope.edit = function(){
    // i need to move editable=!editable into this function
    // but i don't know how to do that
    }

    });

}());
</script>

Solution

  • You could save the editable property of the todo item, and then us it like this.

    $scope.addItem = function(){
        $scope.items.push({text: $scope.newItem,editable:false});
    }; 
    
    $scope.edit = function(item){    
       item.editable = !item.editable; 
       console.log(item)   
    }
    $scope.save = function(item){
      console.log("saved")     
       item.editable = !item.editable; 
     }
    

    html

    <tr ng-repeat="item in items track by $index">
     <td><input ng-disabled="!item.editable" ng-blur="save(item)" type="text" value="{{item.text}}"></td>
    <td ng-click="edit(item)">Edit</td>
    </tr>
    

    I think this is simplest one, but there is always a better approach. Let us know. What is ngBlur