【问题标题】:AngularJS - ng-repeat on objectsAngularJS - 对对象进行 ng-repeat
【发布时间】:2017-03-17 21:59:36
【问题描述】:

我有一个具有 2 个属性的对象列表:标签和描述。在 html 上,我在此列表中循环:

<select class="form-control" 
     ng-options="fid.label for fid in myFidList" 
     ng-model="fidSelected" 
     ng-change="setFidDescription()"/>

我想要做的是调用一个函数 (setFidDescription) 来获取我在选项标签上选择的对象。所以我可以在另一个 div 中更改各自的描述。这似乎不起作用:ng-model 似乎没有更新。功能:

 $scope.setFidDescription = function () {
    console.log($scope.fidSelected);
 }

此代码打印一个空对象。 我错过了什么?另一种方法是获取我选择的 $index。

更多信息: JSON + console

更新: 我发现了我的问题。解释见这里:

AngularJS ngModel doesn't work inside a ui-bootstrap tabset

那是我的问题。

【问题讨论】:

  • 发布你的 json 数据
  • 您是否在以下位置获取控制台正确数据:console.log($scope.fidSelected); ?
  • 不,我打印一个没有属性的对象

标签: javascript angularjs


【解决方案1】:

// Code goes here

angular
  .module('myApp', [])

.controller('testController', ['$scope',
  function($scope) {

    $scope.myFidList = [{
      label: 'label1',
    }, {
      label: 'label2',
    }]

    $scope.setFidDescription = function() {
      alert($scope.fidSelected.label);
    }

  }
])
<!DOCTYPE html>
<html data-ng-app="myApp">

<head>
  <link rel="stylesheet" href="style.css">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body data-ng-controller="testController">



  <select class="form-control" ng-options="fid.label for fid in myFidList" ng-model="fidSelected" ng-change="setFidDescription()"></select>

</body>

</html>

希望这会对你有所帮助。

【讨论】:

  • 感谢您的回复。但我不断得到“未定义”。 fidSelected 为空。
  • @Massimo,在我的例子中也是?
  • 是的,使用您的代码:example。注意:ng-repeat 工作正常
猜你喜欢
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多