Search code examples
angularjsangularjs-ng-repeationic-frameworkng-options

How to set the initial ng-model value for a <select> to pass to function without needing to change the select?


Sorry if this is already answered but I have looked through a lot of questions and just can't get this right.

Using angulaJS with the following declaration to create my select from a JSON object. The select creates perfectly and the item is correctly set using the ng-selected option.

<select ng-model="assignment.status">
            <option ng-selected="instanceData.status.current" ng-repeat="status in instanceData.status.list" value="{{status.id}}">{{status.title}}</option>
</select>

The issue I have is that when I execute an update on ng-click function which passes the value of assignment (ng-model) the value is not being passed to the function unless the select has been changed.

<a class="button button-positive" ng-click="save_status_assignment(assignment)">Update</a>

Is there anyone out there that can help me please?

Many Thanks B


Solution

  • You just need to assign a value to $scope.assignment.status by default.

    Right now, that variable is empty, so it won't give you anything. So something like this in your controller would work

    $scope.assignment = {};
    // Assuming you want the default to be the first value
    $scope.assignment.status = $scope.instanceData.status.list[0].id;
    

    Then you are good to go.

    Edit

    Also, you should use ng-options instead of ng-repeat for your options.

    https://docs.angularjs.org/api/ng/directive/ngOptions