Angularjs自动从模型中选择下拉列表

时间:2013-01-07 16:18:37

标签: angularjs

我正在尝试显示从数据存储区加载的一些数据,但它并未反映UI上的更改。我创建了一个示例来展示我正在努力实现的目标。

http://plnkr.co/edit/MBHo88

以下是angularjs示例的链接,在这些示例中,他们会在点击时显示下拉列表。如果使用列表中的一种颜色替换表达式,则可以很好地选择下拉列表。此类选择仅适用于用户事件吗?

http://docs.angularjs.org/api/ng.directive:select

帮助表示赞赏!!!

3 个答案:

答案 0 :(得分:1)

实际上问题是ngSelect使用简单的比较运算符('==')比较对象,因此具有相同字段和值的两个对象被视为不同的对象。

所以你最好使用字符串和数字作为值(ngSelect指令表达式中的'select'参数)。

这是kind of solution for your plunker

Aslo在GitHub上有关于这个主题的讨论: https://github.com/angular/angular.js/issues/1302 https://github.com/angular/angular.js/issues/1032

另外,我还有一些工作正在进行中,为ngSelect添加自定义比较器/散列,以便能够更轻松地在对象上使用ngSelect。

答案 1 :(得分:0)

控制器初始化中的一个错误。您必须引用palette中的对象,因为这些对象在视图中被观看:

$scope.selectedColors.push({col: $scope.palette[2]});
$scope.selectedColors.push({col: $scope.palette[1]});

与您的result相同:

$scope.result = { color: $scope.obj.codes[2] };

然后你需要观看result。在下面的示例中,select 1接收来自初始选择的值,第二个接收调色板中的下面的值。我不知道这是不是你想要的,但你可以很容易地改变它:

$scope.$watch('result', function(value) {
   if(value) {
      var index = value.color.code -1;
      $scope.selectedColors[0] = {col: $scope.palette[index] };
      $scope.selectedColors[1] = {col: $scope.palette[Math.max(index-1, 0)] };
   }
}, true);

请参阅plunkr

答案 2 :(得分:0)

好吧,我想我想出来了,但感谢@ValentynShybanov和@asgoth。

根据angularjs示例,ngModel使用下拉群体中使用的数组中的一个对象进行初始化。所以有一个数组:

$scope.locations = [{ state: 'FL', city: 'Tampa'}, {state: 'FL', city: 'Sarasota'} ....];

下拉列表定义为:

<select ng-options="l.state group by l.city for l in locations" ng-model="city" required></select>

然后将$ scope.city初始化为:

$scope.city = $scope.locations[0];

到目前为止这么好,对吗?!!! ..但我有多个位置,因此有多个下拉菜单。用户还可以添加/删除更多内容。就像动态创建表一样。而且,我需要从数据存储区加载数据。

虽然我正在构建并分配类似的值(例如:来自数据存储的值 - &gt; State = FL,City = Tampa;因此 - &gt; {state:'FL',city:'Tampa'}) ,angularjs无法匹配该值。我尝试过diff方式,比如只指定{city:'Tampa'}或'Tampa'或者和或或......

所以我做了..而且我知道有点讨厌,但到目前为止工作..是写一个查找函数来返回$ scope.locations的值。因此我有:

$scope.lookupLocation = function(state, city){
   for(var k = 0; k < $scope.locations.length; k++){
      if($scope.locations[k].state == state && $scope.locations[k].city == city)
         return $scope.locations[k];
   }
   return $scope.locations[0]; //-- default value if none matched
}

所以,当我从数据存储区加载数据(json格式的数据)时,我调用lookupLocation函数,如:

$scope.city = $scope.lookupLocation(results[indexFromSomeLoop].location.state, results[indexFromSomeLoop].location.city);

在加载数据时预先选择我的值。这对我有用。

由于