2015-10-14 210 views
0

如何根据ng-options中的ajax结果设置默认值?AngularJS ng-options Ajax默认选择选项

<select ng-model="model.stuff" ng-options="o.name for o in options track by o.id"></select> 

然后在我的控制器我有

$http.get("myurl").then(
    // On Success 
    function(response) { 
     $scope.options = response.data; 
    }, 
    // On Error 
    function(error) { 
     console.log("ERROR"); 
    } 
); 

实例数据会是这样

[ 
    { 
    "id": 1, 
    "name": "Foo" 
    }, 
    { 
    "id": 2, 
    "name": "Bar" 
    } 
] 

时,在我的控制器其他的东西被激活,这得到的是触发,我的选择列表中正确填写,我所有的选择。

但有时我需要在加载ajax数据后设置默认值。例如,我需要从我的数据数组中加载id 1

这并不意味着加载response.data[1]这意味着我必须在response.data之内进行搜索并寻找具有id: 1的项目。这适用于这种方法

function getArrayIndex(key, source){ 
    for (var i = 0; i < source.length; i++) { 
     if (source[i].id == key) { 
      return i; 
     } 
    } 
} 

这会告诉我,response.data[0]id: 1所以我想用它作为我的默认选择的值时,AJAX加载我的数据。

我该如何做到这一点?

我读过一些其他的问题,但我没有什么工作......我试过设置ng-initid值和整个object但不工作...

回答

0

的解决方案是在这里将以下内容添加到您的控制器。

$scope.model = { stuff: null }; 

$scope.$watch('options', function() { 
    if ($scope.options) { 
    $scope.model.stuff = $scope.options[0].name; 
    } 
}); 

要匹配您的示例,请将$ scope.model设置为具有“stuff”键的对象。当$ scope对象的“选项”更改时,$ watch将触发。 'if'语句确保如果'options'被设置为null,则不会发生错误。

有关$ watch的更多信息,请参阅$scope documentation