4

Trying to figure out how to get the id and name of the selected item in angular. Basically brand new to js and angular so not quite sure what I'm doing wrong. I'm sure its something simple I'm missing.

I have an html element that looks like:

 <md-input-container>
     <label>Difficulty</label>
     <md-select ng-model="difficulty" ng-change="update()">
         <md-option ng-repeat="difficulty in difficulties">
             {{difficulty.Name}}
         </md-option>
    </md-select>
</md-input-container>

Calling an api to get the list of difficulties gives back the following json

[{DifficultyID: 1, Name: "Easy"}, {DifficultyID: 2, Name: "Medium"}, {DifficultyID: 3, Name: "Hard"}]

In my controller I have defined the method

$scope.update = function () {
            console.log($scope.item.Name);
        }

Always get an undefined for Name.

2 Answers 2

3

ng-value might be useful in this case. See working Plunker.

<md-select ng-model="difficulty">
     <md-option ng-value="opt" ng-repeat="opt in difficulties" ng-click="update(opt)">
         {{opt.Name}}
     </md-option>
</md-select>

I've introduced opt variable in order to eliminate difficulty duplication. In addition to that I'm doing ng-click on particular option instead of ng-change on parent md-select

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

Comments

2

Your selected option should be in the model you've set in ng-model.

That said to access your selected option you should test your difficulty model in scope

$scope.difficulty 

should hold your selected item.

Want to see it working try

$scope.$watch('dificulty',function(newVal,oldVal){
  console.log($scope.dificulty);
});

On every model change it will get printed. BTW I havent used that directive. But I don't see the ng-change supported on the available properties for that directive.

Hope it helps

2 Comments

Oh, well I can get that to work, except I don't appear to have access to the difficultyID, which is mostly what I'm after.
try Initializing the variable first on your controller . So put $scope.dificulty = someValue

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.