1

Angular doesn't seem to bind my scope variable on load and when I change the select option. I have the currently selected id from the select element, and I want to display the name next to it:

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl">
      <select ng-model="myid" ng-options="c.id as c.name for c in cs"></select>

       <span ng-bind="getName(myid)"></span>

  </div>
</div>

function TodoCtrl($scope) {
    $scope.myid = 1;
    $scope.cs = [ {id:1, name:'one'},
                 {id: 2, name:'two'},
                 {id: 3, name: 'three'}];
    $scope.getName = function(id) {
        angular.forEach($scope.cs, function(c, index) {
           if(c.id == id)
               return c.name
        });

        return "NULL";
    }
}

jsfiddle

Why does the span not update with my scope variable? It's always null when first loading and on any select changes.

1 Answer 1

0

your problem lies in your getName function take a lookt a this fiddle

http://jsfiddle.net/nwtjdffc/

basically i just replace your function with

$scope.getName = function(id) {
   return ($scope.cs.filter(function(item){ 
       return item.id==id})[0]||{}).name
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why does my forEach() not return the name? I thought it would exit the getName() with my name string.
you are always returning NULL in your function you are only returning the name on your foreach callback, but that functions result doesn't propagate to your current function, here is how your foreach could be used jsfiddle.net/mxvaqfs3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.