0

API からリソース データを取得し、それをドロップダウン選択にロードし、ドロップダウンの選択値を設定するという問題がありました。基本的に、ドロップダウンが設定される前にドロップダウンの値を設定しようとしていました。これを行うには2つの異なる方法がありますが、誰かが「より良い」方法、または「より良い練習」の方法を持っているかどうか疑問に思っていました. これが私の2つの方法です。

オプション 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>

どちらがより良い実践であるかについての意見はありますか? または他に良い方法があれば?

4

1 に答える 1

1

だから、約束はこの種のことのあなたの友人です。リソースの代わりに $http を使用するつもりです。なぜなら、私はそれに慣れているからです。しかし、最近のバージョンのリソースは promise を返す (または返すことができる) と確信しています。

また..コントローラーにjqueryはありません。入力値を変更するには、ng-model などのディレクティブを使用します。
また、ng-options を使用して select のオプションを設定することは、「option」要素で ng-repeat を使用するよりも強力です。

ここに私のコードの多くがどのように見えるかを示します (ここでは get ではなく jsonp を使用していることを除いて)。 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>
于 2013-08-02T16:55:11.660 に答える