I\'m pretty new to Angular, so I may be going about this all wrong...
I have a
I think that it will be good it you will use ng-options
attribute of select
tag. It's an angular directive which creates options according to Array of options. You can take a look at select documentation
If you use your code - your function myFunctionForDeterminingWhetherValueIsSelected
works twice for every option at initialization and once for every option item when you select some another option.
Demo for select you could see at description of select
directive.
At first, to see when value is changed - you need to use ng-change
attribute of select
tag, like this:
Then, i don't know how does myFunctionForSettingSelectedValue
look like, but there are 2 variants:
ng-init
next way.Controller:
$scope.someInitFunc = function () {
return 'One';
};
HTML:
mySelectedValue
in this function - then you do this.Controller:
$scope.someInitFunc = function () {
$scope.mySelectedValue = 'One';
};
HTML:
I have created an example which implements the first version of using ng-init
. When new value is selected - it's printed to console.
Also, i moved options to the options.json
file. So options are initialized just after ajax request was finished. Everything works great.
Hello again. I think you don't need to have any ng-init
according to your requirements. You can just initiate values of your model when http request is finished. Also i don't understand why do you need ng-change
function in this case.
Here is modified code you need from your plunk where values of ng-model
s are initiated after options are loaded.
JavaScript:
.controller('MainCtrl', function($scope, $http) {
$scope.someStaticArrayOfValues = ['One', 'Two', 'Three'];
$scope.mySelectedValues = {};
$http.get('options.json').then(
function (response) {
$scope.someDynamicArrayOfValues = response.data;
for (var i = 0; i < $scope.someStaticArrayOfValues.length; ++i) {
$scope.someDynamicArrayOfValues.some(function (value) {
if (value.substring(0, $scope.someStaticArrayOfValues[i].length) === $scope.someStaticArrayOfValues[i]) {
$scope.mySelectedValues[$scope.someStaticArrayOfValues[i]] = value;
return true;
}
});
}
},
function (response) {
console.log('ERROR!');
}
);
});
HTML:
Hello {{name}}!
-
{{staticValue}} -
{{mySelectedValues[staticValue]}}