fanhats
fanhats

Reputation: 797

Angularjs won't bind scope variable with function?

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.

Upvotes: 1

Views: 405

Answers (1)

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

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
}

Upvotes: 0

Related Questions