0

我有一个 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 属性

4

2 回答 2

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

于 2015-11-13T10:06:35.837 回答
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为对象。

PLNKR 上的DEMO

于 2016-09-01T00:34:59.427 回答