MadPhysicist
MadPhysicist

Reputation: 5831

Default Select Option Using JSON Object in Angular

I have the following code that populates a certain select item on a page:

<select ng-model="activity.selectedParent" ng-options="parent as parent.title for parent in parents track by parent._id"></select><br>

I am wondering if it is somehow possible to specify a default option such that I can give it a Title and an ID. For instance, if default is selected, then activity.selectedParent.Title = "None" and activity.selectedParent.id = 0. Is this possible to somehow specify this within the <select> tag using Angular directives? Otherwise, what is the most efficient way of achieving this?

Upvotes: 0

Views: 1234

Answers (2)

developer033
developer033

Reputation: 24874

If I understood well your question you want to set an object even if the default is selected, then you can do it in two ways:

  1. Using ngInit directive inside your select tag, as follows:

    ng-init="selectedParent = { '_id': 0, 'title': 'None' };"

  2. Initializing your object in your controller:

    $scope.selectedParent = { "_id": 0, "title": "None" };

EDIT:

I think I got what you want, now: you want to have a default option instead of a blank as first option, right? If so, you can simply add this element to your existent array, using unshift method, so it'll be placed as first element as below:

$scope.parents.unshift($scope.selectedParent);

Here's a snippet working:

var app = angular.module('app', []);

app.controller('mainCtrl', function($scope) {
  $scope.parents = [  
     {  
        "_id":1,
        "title":"first"
     },
     {  
        "_id":2,
        "title":"second"
     },
     {  
        "_id":3,
        "title":"third"
     },
     {  
        "_id":4,
        "title":"four"
     }
  ];

  $scope.selectedParent = {
    "_id": 0,
    "title": "None"
  };

  $scope.parents.unshift($scope.selectedParent);
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <select ng-model="selectedParent" ng-options="parent as parent.title for parent in parents track by parent._id"></select>
  <hr> 
  Selected: <span ng-bind="selectedParent | json"></span>
</body>

</html>

Upvotes: 1

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16801

If the array used in the ng-options doesn't contain the value you wish to set as default, then the easiest way to achieve this is to add the default value to the array.

First set the selectedParent in the controller

$scope.selectedParent = { "_id": 0, "title": "None" };

Then add it to the first position in the array

$scope.parents.splice(0,0,$scope.selectedParent);

And finaly set the ng-model of the select to ng-model="$scope.selectedParent"

Upvotes: 1

Related Questions