0

I am trying to set ng-selected true in ng-repet my HTML :

    <select ng-model="editActivities.NewArea">
       <option  ng-repeat="area in areas" value="{{area.ID}}" ng-selected="editActivities.Area.ID==area.ID">{{area.Name}}</option>
    </select>

the areas object:

{Name : "City1", ID : "1"}
{Name : "City2", ID : "2"}
{Name : "City3", ID : "3"}

the value of editActivities.Area.ID is 2.

when i print the values in editActivities.Area.ID and in area.ID its print :

1 2 , 2 2 , 2 3 

and still the city2 is not selected.

also i Notice that the selected option is :

<option value="? undefined:undefined ?"></option>

4 Answers 4

1

Based on the details of your question your controller code looks something like:

$scope.areas = [{
  Name: "City1",
  ID: "1"
}, {
  Name: "City2",
  ID: "2"
}, {
  Name: "City3",
  ID: "3"
}];

$scope.editActivities = {
  Area: {
    ID: "2"
  },
  NewArea: "2"
};

That being the case, you can simply use the ng-options directive and let the ng-model binding handle the initial selection, like this:

<select ng-model="editActivities.NewArea" ng-options="area.ID as area.Name for area in areas">

Here's a working plunk

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of using ng-selected you should set the model value, that is set $scope.editActivities.NewArea=2 in your controller. Basically when there is model binded to dropdown it will ignore the ng-seleted first time. If you remove ng-model from select tag, default value will come. Try the following plunker.

without ng-model - https://plnkr.co/edit/0Mj1LHhJgkrluWGQLdBn?p=preview

with ng-mdoel - https://plnkr.co/edit/89PqDYdbfrGwUOHLIGMU?p=preview

Comments

0

You should just use ng-options:

<select ng-model="editActivities.NewArea" ng-options="area as area.Name for area in areas">
</select>

And as usual, the model is the single point of truth in angular. So the selected option is the one stored in editActivities.NewArea. So if you want the first area to be selected, use something like this in your controller:

$scope.editActivities = {
    NewArea: $scope.areas[0]
};

Comments

0

Please do change your ng-selected to the following; there's a comparsion statement('==') instead of assignment('=')

ng-selected="editActivities.Area.ID=area.ID"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.