Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Directive - How to refresh template after async data load

I forked and edited a plunker from this question

What I'm trying to do is to get the SELECT element (combo box) to update/populate once the data has loaded, but something is not right. I retrieve the data, and it is on the scope of the SELECT element, but the template is not refreshing to show the data. Could someone have a look for me and tell my why the template doesn't refresh?

Thanks very much.

The directive:

app.directive('walkmap', function() { 
  return {
    restrict: 'A',
    transclude: true,
    scope: { walks: '=walkmap' },
    template: '<select data-ng-options="w.postalCode for w in walks"></select>',
    link: function(scope, element, attrs)
    {
      scope.$watch('walks', function (walks) {
                scope.walks = walks;
                console.log('watch triggered');
                console.log(scope.walks);


            });

    }
  };
});

The Index.html:

<body ng-controller="MainCtrl">
    <h1>The Walks Data:</h1>
    <div walkmap="store.walks"></div>
  </body>
like image 999
blomster Avatar asked Oct 01 '22 19:10

blomster


2 Answers

Solution:

  • You don't need another $watch, scope: { walks: '=walkmap' } is already watching.
  • When using ngOptions you must use ngModel too.
  • angularjs ng-options not working
  • Working with select using AngularJS's ng-options

here is a plunker:

app.directive('walkmap', function() { 
  return {
    restrict: 'A',
    transclude: true,
    scope: { walks: '=walkmap' },
    template: '<select ng-model="selected" data-ng-options="w.postalCode for w in walks"></select>'
  };
});
like image 97
Ilan Frumer Avatar answered Oct 05 '22 11:10

Ilan Frumer


The problem is with your template. You are yet to define a model which is very important

this should work.

<select data-ng-model="w" data-ng-options="w.postalCode for w in walks"></select>
like image 22
shanks Avatar answered Oct 05 '22 12:10

shanks