使用ng-model

时间:2015-11-13 10:00:20

标签: javascript angularjs radio-button angularjs-ng-value

我有一个json文件

$scope.favoriteThings = [
    {nr: 1, text: "Raindrops on roses"},
    {nr: 2, text: "Whiskers on kittens"},
    {nr: 3, text: "Bright copper kettles"},
    {nr: 4, text: "Warm woolen mittens"},
    {nr: 5, text: "Brown paper packages tied up with strings"},
    {nr: 6, text: "Cream colored ponies"},
    {nr: 7, text: "Crisp apple streudels"},
    {nr: 8, text: "Doorbells"},
    {nr: 9, text: "Sleigh bells"},
    {nr: 10, text: "Schnitzel with noodles"},
    {nr: 11, text: "Wild geese that fly with the moon on their wings"},
    {nr: 12, text: "Girls in white dresses with blue satin sashes"},
    {nr: 13, text: "Snowflakes that stay on my nose and eyelashes"},
    {nr: 14, text: "Silver white winters that melt into springs"}
  ];

- 我正在使用 ng-repeat 指令重复上述数组。

<li ng-repeat="thing in favoriteThings">
        <input type="radio" value="{{thing}}" ng-model="$parent.selected" name="stuff"/>
          {{thing.text}}
      </li>

- 我正在显示通过选中复选框获得的值 Selected thing: {{selected}}{{selected.nr}}

  • 然后我得到以下输出

Selected thing: {"nr":5,"text":"Brown paper packages tied up with strings"} 要访问“nr”属性,我尝试使用{{selected.nr}},但这不起作用 有什么想法吗? 的 PLUNKER LINK 编辑:我还想访问TEXT属性

2 个答案:

答案 0 :(得分:1)

只需编辑您的html正文

即可
      <body ng-controller="MainCtrl">
        <ul>
          <li ng-repeat="thing in favoriteThings">
            <input type="radio" value="{{thing.nr}}" ng-model="$parent.selected" name="stuff"/>
              {{thing.text}}
          </li>
        </ul>
        <hr/>
        Selected thing: {{selected}}  {{getText(selected)}}
      </body>

并将此功能添加到您的控制器

      $scope.getText  = function(_nr){
          var found = $filter('filter')($scope.favoriteThings, {nr: _nr}, true);
          return found[0].text
        }

你可以在这里看到它Plunker

答案 1 :(得分:0)

value属性替换为ng-value指令:

 <body ng-controller="MainCtrl">
    <ul>
     <li ng-repeat="thing in favoriteThings">
        <!-- REPLACE interpolated value
        <input type="radio" value="{{thing}}" ng-model="$parent.selected" name="stuff"/>
        -- with the ng-value directive -->
        <input type="radio" ng-value="thing" ng-model="$parent.selected" name="stuff"/>
          {{thing.text}}
      </li>
    </ul>
    <hr/>
    Selected thing: {{selected}}<br>
    Number: {{selected.nr}}<br>
    Text:   {{selected.text}}
  </body>

通过使用插值value={{thing}}thing对象将转换为字符串。 ng-value指令将thing对象保留为对象。

DEMO on PLNKR