2013-06-27 5 views
-1

ng-repeat 지시문을 사용하여 요소 목록을 표시합니다. 각 요소는 전용 div 블록 내에 표시됩니다. 편집 버튼을 클릭하면 요소 div의 내용이 제출 될 수있는 양식이된다는 것을 의미하는 블록 편집을 허용하고자합니다 ...목록 항목의 동적 버전

컨트롤러에서 dom 조작을 의미하지 않는 Angularjs 철학을 따르고 싶습니다. 오히려 지시문을 사용하십시오 ... ;-)

+2

작성 코드를 작성할 수 없습니다. 지금까지 시도한 것을 알려주세요. –

답변

1

조건부로 요소를 읽기 전용 또는 양식으로 표시하는 한 가지 방법이 있습니다. 그것은이 같은 보일 것이다 :

//The list of elements 
//Id is needed to uniquely identify an item in the list 
$scope.list = [ 
    { 
     id: 1, 
     text: "item_1" 
    }, 
    { 
     id: 2, 
     text: "item_2" 
    } 
]; 

//Contains the ID of the item currently being edited 
//You can have single item that can be in edit mode at one time or 
//you can have multiple items open in edit mode. Go with an array for the latter 
//By default, no item is in edit mode 
$scope.itemIdForEdit = 0; 

//Checks if the item is in edit mode 
$scope.editMode = function (itemId) { 
    return $scope.itemForEdit === itemId; 
}; 

//Changes the item being edited 
$scope.changeToEditMode = function (itemId) { 
    $scope.itemForEdit = itemId; 
}; 

//Edits the item 
$scope.editItem = function (item) { 
    //Logic to update the item in the $scope.list or backend. 
}; 

이 방법, 당신은 당신의 목록에있는 요소의 표시 및 편집을 달성 할 수있다 : 컨트롤러에서

<div ng-repeat="item in list"> 
    <div ng-hide="editMode(item.id)"> 
     <!-- This will contain the DOM elements that 
      will only display the item --> 
     <span>item.text</span> 
     <button type="button" ng-click="changeToEditMode(item.id)"> 
      Edit 
     </button> 
    </div> 
    <div ng-show="editMode(item.id)"> 
     <!-- This will contain DOM elements that will 
      allow editing the item --> 
     <input type="text" ng-model="item.text"> 
     <button type="button" ng-click="editItem(item)"> 
      Save 
     </button> 
    </div> 
</div> 

을 다음과 같은 코드가있을 수 있습니다. 모델을 입력 태그에 지정하면 항목 내용 (내가 좋아하는 AngularJS의 한 기능 - 모델이 자동으로 업데이트되고 명시 적 업데이트 또는 저장이 필요 없음)이 변경됩니다. - 설명 목적으로 만 제공했습니다.

+0

답변 해 주셔서 감사합니다. 따라서 div 블록을 숨기거나 표시해야합니다 ... DOM에서 블록을 추가하고 제거하는 것은 고려할 해결책이 아닙니까? –

+0

너무 추가하고 제거 할 수 있습니다. [여기] (http://docs.angularjs.org/api/ng.directive:ngSwitch)에서 찾을 수있는'ng-switch' 지시어를 확인하십시오. – callmekatootie