Monday, 15 June 2015

javascript - AngularJS directive template not updating if scope is populated via ajax -



javascript - AngularJS directive template not updating if scope is populated via ajax -

i tried give question precise title could. i'm pretty new angularjs i'm stomped on issue. tried create jsfiddle improve illustrate issue relies on many separate files. , alas not online yet, bear verbosity. :) have app built yeoman init angular, , app.js looks this:

"use strict" var myapp = angular.module("myapp", []) .config(function($routeprovider) { $routeprovider .when("/lineup", { templateurl: "views/lineup.html", controller: "lineupctrl" }) //other routes .otherwise({ redirectto: "/" }); }) .directive("playerlist", function() { homecoming { restrict: "e", transclude: false, scope : {}, templateurl : "views/directives/playerlist.html", controller : function($scope) { $.get("/players") .success(function(players) { $scope.players = players; }); }, replace : true } });

my index.html picks app.js , has anchor references #/lineup, opens views/lineup.html; simplify things, let's assume latter contains (custom) <playerlist></playerlist> tag. within directive's controller function i'm sure $.get("/players") works should because can see chrome's network tab response comes through correctly array of players. finally, views/directives/playerlist.html has code replaces <playerlist> tag, follows:

<table class="table table-striped"> <thead> <tr> <th>name</th> <th>age</th> <th>role</th> <th>strength</th> </tr> </thead> <tbody> <tr ng-repeat="player in players"> <td>{{player.first_name}} {{player.last_name}}</td> <td>{{player.age}}</td> <td>{{player.role}}</td> <td>{{player.strength}}</td> </tr> </tbody> </table>

my thought create "playerlist" directive independent lineupctrl might want reuse elsewhere in project. ok here goes: when click on anchor loads #/lineup first time, tbody element of above table empty (no rows appended it); funny thing is, when click on sec time, table correctly populated players $.get("/players") instruction. suspect due slight lag occurs between rendering of playerlist.html , $scope.players variable beingness assigned. isn't whole point of angular app? when scope variables alter respective views (and templates) updated? please help! cheers, andrea

whenever update scope variables outside of angular function, need tell angular changed. see scope.$apply.

$.get("/players") .success(function(players) { $scope.$apply(function () { $scope.players = players; }); });

on different note, angular has built in ajax service, there no need utilize jquery. explanation can found in tutorial: 5 - xhrs & dependency injection.

javascript angularjs

No comments:

Post a Comment