Angular expression send by id

On Select/Option onchange() event it should write the value of the JSON file as an angular expression to test ID div.

However it writes like it's just a string: {{names[1].thnev}} (And if I put this manually into the ID div, it works.)

Can you help me what did I miss? (In the last 4 hours...) Thank you.

<div ng-app="myApp" ng-controller="customersCtrl">      
    <select id="thaz" name="thaz" class="selectbox" onchange="onChange(this.value)">
        <option ng-repeat="x in names" value="{{x.id}}">{{x.id}} - {{x.thnev}}</option>
    </select>

    <div id="list"></div>

</div>

<script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http) {
        $http.get("al_list_th.php")
        .then(function (response) {$scope.names = response.data.records;});
    });

    function onChange(value) {
        document.getElementById("list").innerHTML = "{{names[" + value + "].thnev}}";   
    }
</script>

Upvotes: 0

Views: 180

Answers (1)

Christian Santos
Christian Santos

Reputation: 5456

We can use the built-ins that AngularJS has available to simplify the problem.

In this case, we can use ngModel to bind the value of the select into a variable that we can use in our template. Let's call this variable selectVal.

Then, we can write {{names[selectVal].thnev}} directly inside of the div that we want this output to live in.

I've put together this example to show the changes:

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

app.controller('customersCtrl', function($scope, $http) {

  $scope.selectVal = "default";
  $scope.names = [{id: 0, thnev: 5}, {id: 1, thnev: 6} ];

  //$http.get("al_list_th.php")
    //.then(function (response) {$scope.names = response.data.records;});
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>

<div ng-app="myApp" ng-controller="customersCtrl"> 
     
    <select id="thaz" name="thaz" class="selectbox" ng-model="selectVal">
        <option value="default">None</option>
        <option ng-repeat="x in names" value="{{x.id}}">{{x.id}} - {{x.thnev}}</option>
    </select>

    <div id="list">
    	{{names[selectVal].thnev}}
    </div>

</div>

Note: In my code I added an extra option so that there would be a default as opposed to a blank initial dropdown. You don't have to do this -- the code will work the same without it.

Upvotes: 1

Related Questions