Hacker
Hacker

Reputation: 7906

Not able to get select value in scope

I have code like one attached in js fiddle. It is very basic, I am trying to get value of the select when it changes using scope variable. But i am not able to.Is there any specific reason why it is not working.

    <div ng-controller="myCtrl">
        <select
            ng-model="myOption"
            ng-options="value.id as value.label group by value.group for value in myOptions" ng-change="selectedValue()">
                <option>--</option>
        </select>
        <div>
            ng-model value: {{myOptionnew}}
        </div>
    </div>

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

function myCtrl($scope) {
    $scope.myOptions = [{
            "id": 106,
            "group": "Group 1",
            "label": "Item 1"
        },{
            "id": 107,
            "group": "Group 1",
            "label": "Item 2"
        },{
            "id": 110,
            "group": "Group 2",
            "label": "Item 3"
        }];

    $scope.selectedValue = function()
    {
        alog($scope.myOption);   
        $scope.myOptionnew = $scope.myOption;
    }
};

http://jsfiddle.net/jm6of9bu/1107/

Upvotes: 1

Views: 790

Answers (2)

Michel
Michel

Reputation: 28269

In the fiddle the function alog is not defined. Therefore the assignment that follows doesn't occur.

Remove alog or replace it with $log.log : fiddle

As a side note, you also need to add value="" to the default empty option if you want it to be displayed:

 <option>--</option>

should be:

<option value="">--</option>

Upvotes: 1

Oj G
Oj G

Reputation: 39

HTML:

<div ng-controller="myCtrl">
<select
    ng-model="myOption"
    ng-options="value.id as value.label group by value.group for value in myOptions">
        <option>--</option>
</select>
<div>
    ng-model value ID: {{myOptionnew}}
</div>

JS :

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

function myCtrl($scope) {
    $scope.myOptions = [{
            "id": 106,
            "group": "Group 1",
            "label": "Item 1"
        },{
            "id": 107,
            "group": "Group 1",
            "label": "Item 2"
        },{
            "id": 110,
            "group": "Group 2",
            "label": "Item 3"
        }];

     $scope.$watch('myOption', function(result){
            if (result)
            $scope.myOptionnew = result;
        });
};

I used $watch try this!

Upvotes: 0

Related Questions