2013-02-12 3 views
7

에 객체를 변환 내가 내 HTML 파일에 다음과 같습니다AngularJS와 겨 모델 문자열

<td style="width: 200px;"> 
     <span ng-repeat="list in listGroups"> 
      <label for="{{ list.description }}" />{{ list.description }}</label> 
      <input ng-model="$parent.listGroup" id="listGroup-{{ list.value }}" name="listGroups" value="{{ list }}" type="radio" /> 
     </span> 
    </td> 

listGroups가 포함

[ 
    { 
     "description": "New by Territory", 
     "group": "product", 
     "type": "new" 
    }, 
    { 
     "description": "New by Genre", 
     "group": "genre", 
     "type": "new" 
    }, 
    { 
     "description": "Charts by Territory", 
     "group": "product", 
     "type": "chart" 
    }, 
    { 
     "description": "Charts by Genre", 
     "group": "genre", 
     "type": "chart" 
    } 
] 

나는 NG의 라디오 버튼을 listGroup (설정을 클릭하면 - 모델) 예를 들어,이된다 :

{"description":"New by Genre","group":"genre","type":"new"} 

내가 typeof $scope.listGroup와 listgroup을보고, 나는 그것이 인 것을 알 지금 끈!

이와 같이 나머지 HTML 페이지의 다른 바인딩에있는 속성에 액세스 할 수 없습니다. 이 경우

, 나는 어떻게 객체로 객체를 유지하다, 그것이 내가하고 싶은 일을해야합니까, 더 중요한 것은, 여기에서 일어나고있는 일 이죠 ng-show="listGroup.group == 'genre'"

줄까?

덕분에 모든

데이브

답변

1

왜 당신이 NG-모델로 객체를 갖고 싶어합니까? ng-model은 문자열에서만 작동하기 때문에 listGroup 변수가 문자열이됩니다. 당신은 당신이 NG-모델을 사용하려면 복잡한 객체가있는 경우, 당신은 지시를 생성하고이 같은 파서와 포매터를 구현해야합니다 How to do two-way filtering in angular.js?

4

문제는 입력의 value 속성은 문자열을 허용한다는 것입니다 , 아니 개체 (확인 here). 당신이 이것을 할 때 : value="{{ list }}", 당신은 기본적으로 input.value = list.toString()하고있다.

한 가지 가능한 해결 방법은 ng-repeat 지시문의 $index을 사용하는 것입니다. 예 : http://jsfiddle.net/bmleite/cKttd/

+0

또한 '$ parent.'를 사용하지 마십시오. 그러면 나중에 문제가 발생할 수 있습니다. – bmleite

1

이제 ng-value을 사용할 수 있습니다.

<input ng-model="$parent.listGroup" id="listGroup-{{ list.value }}" name="listGroups" ng-value="{{ list }}" type="radio" />

0

또한 JSON.parse (객체의 문자열),하지만 난 더 나은 솔루션을 @bmleite처럼 생각 할 수있다. 이걸 그냥 던지면 누군가 다른 케이스를 사용하게됩니다.

관련 문제