AngularJS下拉列表未显示选定值 [英] AngularJS dropdown not showing selected value

查看:142
本文介绍了AngularJS下拉列表未显示选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角度下拉列表中显示所选值时遇到问题。
当我给这样的时候它起作用

Am facing problem in displaying selected value in angular dropdown. it works when i give like this

$scope.selectedItem = $scope.items[1];

无效,如果我直接给出该值

not working, if i give directly that value

$scope.selectedItem = { name: 'two', age: 27 };

HTML

<html ng-app="app">
  <body>
    <div ng-controller="Test">
      <select ng-model="selectedItem" ng-options="item.name for item in items">
      </select>
    </div>
  </body>
</html>

JS

var app = angular.module('app',[]);
app.controller('Test',function($scope){
   $scope.items = [{name: 'one', age: 30 },{ name: 'two', age: 27 },{ name: 'three', age: 50 }];
  $scope.selectedItem = $scope.items[1];
});

CODEPEN:
http://codepen.io/anon/pen/zxXpmR

解决方案:

谢谢samir-das。我根据你的建议修好了。

Thank you samir-das. I fixed as per your suggestion.

var choosen_value = { name: 'two', age: 27 };
angular.forEach($scope.items, function(item){
  if(angular.equals(choosen_value, item)){
    $scope.selectedItem = item;
  }
});


推荐答案

好吧,因为

$ scope.items [1] {name:'two',年龄:27} 是完全不同的事情。

$scope.items[1] and { name: 'two', age: 27 } is totally different thing.

{name:'two',年龄:27} 是完全不同的对象,而 $ scope.items [1] 是对象的一部分 $ scope.items

{ name: 'two', age: 27 } is a totally different object whereas $scope.items[1] is part of the object $scope.items

当您使用 {{}} 在模板中放置某些内容时,angular会将其添加到其观察者列表中。

When you put something in the template using {{}}, angular add it in its watcher list.

因此当角度将它放入监视列表时,它就是一个对象(即 {name:'two',年龄:27} )与 $ scope.items 不同。

SO when angular put it in the watch list, it was an object (i.e. { name: 'two', age: 27 } ) that is different than $scope.items.

selectedItem 附加了您在控制器中设置的对象。总之,在脏检查时,angular将检查 selectedItem {name:'two',年龄:27} 不反对 $ scope.items

selectedItem is attached with the object that you set in the controller. In summary while dirty checking, angular will checks selectedItem against { name: 'two', age: 27 } NOT against $scope.items

希望你明白我的意思

这篇关于AngularJS下拉列表未显示选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆