【问题标题】:Angularjs ng-repeat race condition in setting dropdown valueAngularjs ng-repeat 设置下拉值的竞争条件
【发布时间】:2013-08-03 23:53:37
【问题描述】:

我遇到了从 API 获取资源数据、将其加载到下拉选择中并设置下拉选择值的问题。基本上它试图在填充下拉列表之前设置它的值。我有两种不同的方法可以做到这一点,但想知道是否有人有“更好”的方法,或者“更好的实践”方法。这是我的两种方法。

选项 1:附加到 ng-repeat 元素的指令

控制器

$scope.users = User.query();
$scope.dude={
    name: "Dude",
    id: 3
}

HTML

<select id="userSelect" ng-show="users.length">
    <option ng-repeat="user in users" choose dude="dude">{{user.username}}</option>
</select>

指令

.directive('choose', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            if (scope.user) {
                if (scope.user.id === scope.dude.id) {
                    $("#userSelect").val(element.val());
                }
            }
        }
    }
});

选项 2:观察用户长度的变化(返回调用,并填充下拉菜单)

控制器

$scope.users = User.query();
$scope.dude={
    name: "Dude",
    id: 3
}
$scope.$watch('users.length', function() {
    $("#userSelect").val($scope.dude.id);
});

HTML

<select id="userSelect" ng-show="users.length">
    <option ng-repeat="user in users" value="{{user.id}}>{{user.username}}</option>
</select>

关于哪个更好的做法有什么意见吗?或者有没有其他更好的方法?

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-ng-repeat


    【解决方案1】:

    所以,promise 是这类事情的朋友。我将使用 $http 而不是资源,因为我更熟悉它,但我很确定最近的版本 资源返回承诺(或可以)。

    另外.. 你的控制器中没有 jquery。使用像 ng-model 这样的指令来改变输入值。
    此外,使用 ng-options 填充 select 的选项比在“option”元素上使用 ng-repeat 更强大。

    这就是我的很多代码的样子(除了我在这里使用 jsonp 而不是 get)。 http://jsfiddle.net/HB7LU/142/

    控制器:

    function MyCtrl($scope, $http) {
        // The id we want to select when the data loads:
        var desiredId = 3;
    
        // Overly complicated $http request so that I can load with jsonp:
        // You could normally use just $http.get()
        $scope.users = $http.jsonp('http://www.json-generator.com/j/geku?callback=JSON_CALLBACK').then(function(d) { return d.data.result; });
    
        // Use the returned promise to set the selection when the data loads:
        // I'm using the "underscore" library function "findWhere" to set my
        // model to the object I want selected:
        $scope.users.then(function(d) {
            $scope.uservalue = _.findWhere(d,{id:desiredId});
        });
    
    }
    

    HTML:

    <div ng-controller="MyCtrl">  
        {{uservalue | json}}
        <select ng-model="uservalue" ng-show="users.length" ng-options="user.name for user in users">
        </select>
    </div>
    

    【讨论】:

    • 我喜欢。在回调中设置范围变量更有意义。当我把事情复杂化时,我喜欢它。谢谢大佬。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多