I can't get the ng-init directive in my select picker with AngularJs. No option is selected even id productQuantity/unitName has a value.
Here how my JSON Object is formed:
inventoryLines: Array[1]
0: Object
permitedFormatUnits: Array[2]
0: Object
unitName: "Kilo"
1: Object
unitName: "Gramme
productQuantity: Object
formatUnit: Object
unitName: "Gramme"
quantity: 456
I need the permitedFormatUnits to be the choices that the user can make and the productQuantity/formatUnit to be the ng-init value and the ng-model value has well.
Here's my html where line represents an inventoryLines in a ng-repeat loop:
<select class="selectpicker" name="unitFormat"
ng-init="formatUnit = line.productQuantity.formatUnit.unitName"
ng-model="line.productQuantity.formatUnit"
ng-options="formatUnit as formatUnit.unitName for formatUnit in line.permitedFormatUnits">
</select>
Thanks you very much for your help, hope I have been clear enough! :
Here is a working plunkr: http://plnkr.co/edit/TyWqjW2KQ0LEngWX9uVx
You need to use the track by
to make it work (see the doc - https://docs.angularjs.org/api/ng/directive/select):
<select class="selectpicker" name="unitFormat"
ng-init="formatUnit = line.productQuantity.formatUnit"
ng-model="line.productQuantity.formatUnit"
ng-options="formatUnit as formatUnit.unitName for formatUnit in line.permitedFormatUnits track by formatUnit.unitName">
</select>
the js:
angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.line = {
permitedFormatUnits: [{
unitName: "Kilo"
}, {
unitName: "Gramme"
}],
productQuantity: {
formatUnit: {
unitName: "Gramme",
quantity: 456
}
}
}
})