2016-10-20 16 views
0

私は選択ボックスを角度で動作させようとしています。私が経験している問題は、ng-initを使って実行時に作成されるオブジェクトからデフォルト値を設定することです。 HERESに私のコード:角度選択、動的値のng-init

 <select 
      ng-model="settings.editing.panel.data.production_company" 
      ng-change="settings.editing.panel.data.production_company = selectValue" 
      ng-init="selectValue = settings.editing.panel.data.production_company" 
     > 
      <option 
       ng-repeat="(key, value) in lists.production_companies" 
       value="{{key}}" 
       ng-selected="{{selectValue}}" 
       > 
        {{value}} 
       </option> 
     </select> 

「lists.production_companiesは、」AJAXによって更新された最初のページのレンダリング、中に取り込ま名前のシンプルなキーと値の配列は、あります。

オブジェクト "settings.editing.panel.data"は寿命としてNULLを開始しますが、後でプロパティ "production_company"を含む正しくフォーマットされたオブジェクトがロードされます。

"ng-init =" selectValue = 3 "のような設定にng-initが設定されていますが、$ scope.test = 3を設定して" ng-init = "selectValue = test"あまりにも。

ただし、私の動的値は機能しません。私は動的に作成されたオブジェクトを使用して、実行時にこのセレクトボックスの値を設定することができますか?

+0

代わりにngOptionsを使用してください。 – Grundy

+0

ng-changeを使用して値を維持する場合、なぜng-modelを使用するのですか? selectコンポーネントのng-modelの作業について読む。 –

+0

これは私の誤解の一部であり、未知の理由で動作しないモデルと関係しています。私はそれ以来、問題を解決することでこれを解決しました。この場合、モデルが実行時間の開始後にajaxを介してロードされていた場合、私のモデルは最初に設定されていませんでした。 – kirgy

答えて

0

私は次のようにオブジェクトを設定するために私のバックエンドのデータフォーマットを変更することができました:

{"id": 1, "name":"prod comp 1"} 

を入力し、それに応じて選択モデルを変更します。後見では、私はIDのためにこれを必要としました。

<select 
    ng-model="settings.editing.panel.data.production_company" 
> 
    <option 
     ng-repeat="option in settings.lists.production_companies" 
     value="{{option.id}}" 
     ng-selected="{{option.id}} == settings.editing.panel.data.production_company" 
    > 
     {{option.name}} 
    </option> 
</select> 
0

何とか私に混乱してください。次のスニペットはworkingです。それはあなたが望むものですか?私の状況では

'use strict'; 
 
angular.module('DemoApp', []); 
 
angular.module('DemoApp').controller('DemoCtrl', ['$scope', function($scope){ 
 
    $scope.lists={ 
 
    \t production_companies: { "0": "prod 1", "1":"prod_2" }, 
 
    }; 
 
    $scope.settings={ 
 
    \t editing: { 
 
    \t panel: { 
 
     \t data: null 
 
     } 
 
    } 
 
    }; 
 
    $scope.setData=function(data){ 
 
    $scope.settings.editing.panel.data={ 
 
     production_company: data 
 
    }; 
 
    }; 
 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="DemoApp" ng-controller="DemoCtrl"> 
 
<select ng-model = "settings.editing.panel.data.production_company"> 
 
    <option ng-repeat = "(key, value) in lists.production_companies" value = "{{key}}">{{value}}</option> 
 
</select> 
 
<div>You select: {{settings.editing.panel.data.production_company}}</div> 
 
<button ng-click="setData('0')">Set Data to Prod1</button> 
 
<button ng-click="setData('1')">Set Data to Prod2</button> 
 
</div>

+0

settings.editing.panel.dataは、次のようにボタンのクリック中に設定されます: "$ scope.settings.editing.panel.data = angular.copy(object)"、これは私が理解するように、これが原因です