2015-10-10 97 views
1

此問題已被多次詢問,但我認爲這裏的場景有點不同,我試圖按照accepted answer in this question。與此處不同的是,我的數據是從api獲取的,因此我無法將這樣的屬性添加到數據中,例如 item.editing。我嘗試將對象/事件傳遞給函數,但這不是解決它的角度方式,我想。使表格單元格可編輯雙擊 - Angularjs

function myCtrl($scope) { 
 

 
    $scope.items = [{ 
 
     name: "item #1", 
 
    }, { 
 
     name: "item #2", 
 
    }, { 
 
     name: "item #3", 
 
    }]; 
 
     
 
    $scope.editItem = function (obj) { 
 
     obj.target.setAttribute("ng-hide", true); 
 
     // doing something like? but this wouldn't be angular way 
 
\t \t //obj.target.next().setAttribute('ng-show', false); 
 
    } 
 

 
    $scope.doneEditing = function (item) { 
 
\t \t obj.target.setAttribute("ng-show", false); 
 
     //obj.target.previous().setAttribute("ng-hide", false); 
 
    }; 
 
}
.container { 
 
    margin-top:10px; 
 
    font-family:arial; 
 
} 
 
input:focus { 
 
    //change more attributes, if you want. 
 
} 
 
input { 
 
    border:none; 
 
    background-color:transparent; 
 
} 
 
.container header { 
 
    padding-bottom:20px; 
 
    border-bottom:1px solid black; 
 
} 
 
ul, input, .container { 
 
    padding:10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app ng-controller="myCtrl" class="container">Double-click on the items below to edit: 
 
     <table> 
 
     <tr ng-repeat="item in items"> 
 
      <td> 
 
      <!-- How to do this Angular way? Instead of giving ng-hide as false statically, give some parameter to it, which can be modified from functions editItem, and doneEditing -->  
 
       <span ng-hide="false" ng-dblclick="editItem($event)">{{item.name}}</span> 
 
       <input ng-show="false" ng-model="item.name" ng-blur="doneEditing($event)" autofocus /> 
 
      </td> 
 
     </tr> 
 
     </table> 
 
</div>

on fiddle

+0

怎麼樣儘量[UI網(http://ui-grid.info/)或一些其他圖書館,而不是自己處理所有這些問題 – Haocheng

+0

@Hoocheng我想要把它作爲最後的手段,我想,我不是真的除了這個之外,我的表中還需要其他任何功能,所以儘量讓它保持輕微。感謝您的建議,但! –

回答

2

試試這一個Demo

function myCtrl($scope) { 

    $scope.items = [{ 
     name: "item #1", 
    }, { 
     name: "item #2", 
    }, { 
     name: "item #3", 
    }]; 

    $scope.editItem = function (obj) { 
     console.log(obj.target); 
     obj.target.setAttribute("contenteditable", true); 
     obj.target.focus(); 
     // doing something like? but this wouldn't be angular way 
     //obj.target.next().setAttribute('ng-show', false); 
    } 
} 
+0

太棒了,這樣做恰到好處。謝謝! –