Non-functioning view when sharing controller - javascript

I have a simple app that fetches images from Flickr and renders them. The application is divided into two views, SearchView and PhotoListView. Previously, when treating these as one view, everything worked fine, and photos were rendered. Now, when sharing controller, both are rendered but the list of photos is never populated. When debugging I can see that the photos are indeed fetched.
I'm terribly new at Angular, so I really don't have any good guesses at what the problem could be, but possibly that the two views don't share scope properly?
Here's the routing (using ui-router):
// app.js
'use strict';
angular.module('pruApp', ['ui.state'])
.config(function ($httpProvider, $stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/photos');
$stateProvider
.state('/', {
url: '/photos',
views: {
'SearchView': {
templateUrl: '/views/search.html',
controller: 'PhotoCtrl'
},
'PhotoListView': {
templateUrl: '/views/photo-list.html',
controller: 'PhotoCtrl'
}
}
});
// Remove X-Requested-With header to enable CORS
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
The controller and factory that talks to the Flickr service:
// photo.js
'use strict';
angular.module('pruApp')
.controller('PhotoCtrl', function ($scope, PhotoFactory) {
$scope.search = function() {
PhotoFactory.getPhotos($scope.searchQuery).then(function (data) {
$scope.photos = [];
var parsedData = angular.fromJson(data);
var items = parsedData.photos.photo;
for (var i = 0; i < items.length; ++i) {
var photo = items[i];
$scope.photos.push({
title: photo.title,
image: 'http://farm' + photo.farm + '.staticflickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_m.jpg',
link: 'http://www.flickr.com/photos/' + photo.owner + '/' + photo.id
});
}
});
};
});
angular.module('pruApp')
.factory('PhotoFactory', function ($http, $q) {
return {
_get: function(url) {
var deferred = $q.defer();
$http.get(url)
.success(function (data) {
deferred.resolve(data);
})
.error(function (data, status) {
deferred.reject('An error occured: ' + status);
});
return deferred.promise;
},
getPhotos: function (searchQuery) {
return this._get('http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=<MY_KEY>&tags=' + searchQuery + '&format=json&nojsoncallback=1');
}
};
});
This is where the views are injected:
<!-- index.html -->
<div class="main" role="main">
<div class="search" ui-view="SearchView"></div>
<div class="results" ui-view="PhotoListView"></div>
</div>
Search template:
<!-- search.html -->
<h2 class="struct">Search</h2>
<form>
<fieldset>
<div class="cell">
<input type="search" name="search-query" class="search-query" placeholder="Search photos by tags (e.g. lolcat, rageface, bronie)" ng-model="searchQuery" required>
</div>
<div class="cell">
<button type="submit" name="search-button" class="search-button" ng-click="search()">Search</button>
</div>
</fieldset>
</form>
Photo list template:
<!-- photo-list.html -->
<h2 class="struct">Search results</h2>
<ul>
<li ng-repeat="photo in photos">
<h3>{{ photo.title }}</h3>
<img ng-src="{{ photo.image }}" alt="{{ photo.title }}">
<p class="author">Author: <span>{{ photo.author }}</span></p>
</li>
</ul>

So your problem seems to be that you are calling the method to get the photos on one instance of the controller but that doesn't share data with your other controller. On first read I had missed your factory definition, still the problem is the variable in scope on the controller is in a different instance.
The way you can handle this is by always returning a promise from the factory/service to the controller, the in the controller using the promise to assign the scope. This way if the service has data already available it will automatically populate in your controllers scope, and if not as soon as it comes available it can be populated.
Really it looks like you're doing what I'm saying in the paragraph above but I don't see where the search function is called within the controller. Essentially you should just have something in the controller that is populating the $scope.photos array directly off the service. Then separately you should have your search function which fires off the call to the service passing along the parameter.
Another option is to $watch your properties in the factory/service and update a variable in the $scope of the controller on changes.
angular.module('pruApp')
.factory('PhotoFactory', function ($http, $q) {
return {
photos: [],
_get: function(url) {
var deferred = $q.defer();
$http.get(url)
.success(function (data) {
this.photos = [];
var parsedData = angular.fromJson(data);
var items = parsedData.photos.photo;
for (var i = 0; i < items.length; ++i) {
var photo = items[i];
this.photos.push({
title: photo.title,
image: 'http://farm' + photo.farm + '.staticflickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_m.jpg',
link: 'http://www.flickr.com/photos/' + photo.owner + '/' + photo.id
});
}
deferred.resolve(data);
})
.error(function (data, status) {
deferred.reject('An error occured: ' + status);
});
return deferred.promise;
},
getPhotos: function (searchQuery) {
return this._get('http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=<MY_KEY>&tags=' + searchQuery + '&format=json&nojsoncallback=1');
}
};
});
and in the controller
angular.module('pruApp')
.controller('PhotoCtrl', function ($scope, PhotoFactory) {
$scope.$watch(function () { return PhotoFactory.photos; }, function(data) {
$scope.photos = data;
}); // initialize the watch
$scope.search = function() {
PhotoFactory.getPhotos($scope.searchQuery);
};
}
});

Related

Why are the functions being called in my angular html bindings receiving null values?

I am creating a simple web app that represents something like a trip planner. Just offers some simple itinerary options from a list of locations in a DB I made. My feed page is supposed to display pictures of each attraction, and each attraction is a clickable card that will lead you to another page with some more info on that attraction.
//
// init app
var tripperApp = angular.module('tripperApp', ["ui.router", 'ionic', 'LocalStorageModule']);
//
// setup routing
tripperApp.config(function($stateProvider, $urlRouterProvider) {
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise("/splash");
// Now set up the states
$stateProvider
.state('splash', {
url: "/splash",
templateUrl: "partials/splash.html",
controller: "splashCtrl"
})
.state("login", {
url: "/login",
templateUrl: "partials/login.html",
controller: "loginCtrl"
})
.state("signup", {
url: "/signup",
templateUrl: "partials/signup.html",
controller: "signupCtrl"
})
.state("reset-password", {
url: "/reset-password",
templateUrl: "partials/reset-password.html",
controller: "resetPasswordCtrl"
})
.state("set-password", {
url: "/set-password/:user_id/:password_reset_hash",
templateUrl: "partials/set-password.html",
controller: "resetPasswordCtrl"
})
.state("feed", {
url: "/feed",
templateUrl: "partials/feed.html",
controller: "feedCtrl"
})
.state("wishlist", {
url: "/wishlist",
templateUrl: "partials/feed.html",
controller: "wishlistCtrl"
})
.state("specificwishlist", {
url: "/wishlist/:user_id",
templateUrl: "partials/feed.html",
controller: "wishlistCtrl"
})
.state("share", {
url: "/share",
templateUrl: "partials/share.html",
controller: "shareCtrl"
})
.state("attraction", {
url: "/attraction/:attraction_id",
templateUrl: "partials/attraction.html",
controller: "attractionCtrl"
});
});
This is my app.js file where I initialize all my routings and controllers. I think I am literally having problems with everything (I have a backend and everything in Nodejs, but that isn't working right because all of the values it receives is null - more on that later...).
The main problem I am seeing is that nearly all the data I am receiving is null. Nothing is really loading right - but I know that I have a proper connection to my DB. Because there are some places where I can see the correct results. Let me explain:
This is my services/feed.js file (I don't think it's very important):
//
// feed service: used to get setup filters and then query for a feed using those filters
tripperApp.factory("feedService", ["$rootScope", "api", function($rootScope, api) {
var feedService = {};
api.get("filters").success(function(data, status, headers, config) {
$rootScope.filters = data;
})
.error(function(data, status, headers, config) {
// #TODO - gracefully handle error
});
feedService.runSearch = function($rootScope, session, callback) {
// add on more results
api.post("search", {
"start": $rootScope.currentSpot
})
.success(function(data, status, headers, config) {
// copy results into array
for (var i = 0; i < data.length; i++) {
$rootScope.results.push(data[i]);
}
$rootScope.currentSpot += data.length;
// call callback
callback(true); // success!
})
.error(function(data, status, headers, config) {
callback(false); // error!
});
};
feedService.getWishlist = function($rootScope, session, callback) {
// get all results
api.post("wishlist", {
"attraction_ids": session.picks
})
.success(function(data, status, headers, config) {
// copy results into array
$rootScope.results = data;
callback(true); // success!
})
.error(function(data, status, headers, config) {
callback(false); // error!
});
};
// column-related functions
$rootScope.columns = function() {
var columns = 1;
var windowWidth = window.innerWidth;
if (windowWidth > 1300) {
columns = 5;
} else if (windowWidth > 1100) {
columns = 4;
} else if (windowWidth > 640) {
columns = 3;
} else if (windowWidth > 300) {
columns = 2;
}
var rv = [];
for (var i = 0; i < columns; i++) {
rv.push(i);
}
return rv;
}
$rootScope.getColumn = function(data, columnNumber) {
var columns = $rootScope.columns().length;
var rv = [];
for (var i = columnNumber; i < data.length; i += columns) {
rv.push(data[i]);
}
return rv;
}
$rootScope.columnClasses = function() {
var columns = $rootScope.columns().length;
return {
"col-33": (columns == 3),
"col-25": (columns == 4),
"col-20": (columns == 5),
"col-50": (columns == 2)
};
}
// generate thumbnail of a url
$rootScope.thumb = function(filename) {
return filename + ".thumb.jpeg";
}
return feedService;
}]);
This is my controller (controller/feed.js) file:
//
// feed controller
tripperApp.controller("feedCtrl", function($scope, $rootScope, session, feedService, $ionicScrollDelegate) {
// setup feed page (only once)
if (typeof($rootScope.feed) == "undefined") {
// first time loading - setup scope
$rootScope.feed = {
results: [],
currentSpot: 0
}
}
// auto scroll down (if appropriate)
window.setTimeout(function() {
if (typeof($rootScope.feed.lastScrollPosition) != "undefined") {
$ionicScrollDelegate.$getByHandle('feedScroll').scrollTo(0, $rootScope.feed.lastScrollPosition, false);
}
}, 0);
// tell feed template that this is NOT for a wish
$scope.wishlist = false;
// don't display share button on feed
$scope.displayShare = function() {
return false;
}
// query and display results
$scope.loadResults = function() {
feedService.runSearch($rootScope.feed, session, function(success) {
if (!success) {
// #TODO - handle error
}
$scope.$broadcast('scroll.infiniteScrollComplete');
});
}
// whether an attraction is picked
$scope.attractionIsPicked = function(attraction_id) {
return session.picks.indexOf(attraction_id) != -1;
};
// when a result is picked/unpicked
$scope.resultPicked = function(result) {
var attraction_id = result.id;
console.log(result);
console.log(attraction_id);
if (session.picks.indexOf(attraction_id) == -1) {
// not yet picked, so lets pick it
session.pickPlace(attraction_id);
} else {
// its picked, so lets unpick it
session.unpickPlace(attraction_id);
}
}
$rootScope.clickedResult = undefined;
$scope.resultClicked = function(result) {
$rootScope.clickedResult = result;
console.log("result: \n");
console.log(result);
$rootScope.feed.lastScrollPosition =
$ionicScrollDelegate.$getByHandle('feedScroll').getScrollPosition().top;
}
});
There are a couple of functions I am specifically having problems with:
resultPicked() in controller/feed.js and thumb() in services/feed.js. I am getting null values for both of these.
My partial/feed.html file is as such:
<ion-view>
<ion-header-bar class="bar bar-positive" align-title="center">
<div class="buttons">
<button class="button ion-navicon-round button-light" ng-click="toggleLeftMenu(); " style="font-size: 22px"></button>
</div>
<h1 class="title" ng-show="wishlist==false">New York Attractions</h1>
<h1 class="title" ng-show="wishlist==true">
<span ng-show="feed.user.name == 'Your'">Your</span>
<span ng-show="feed.user.name != 'Your'">{{feed.user.name}}'s</span>
Wish List
</h1>
<div class="buttons" ng-show="displayShare()">
<button class="button ion-android-share button-light" style="font-size: 22px" ng-click="sharePage();"></button>
</div>
</ion-header-bar>
<ion-content class="padding feed-page" delegate-handle="feedScroll">
<ion-list>
<!-- display results in columns -->
<div class="row">
<div class="col" ng-class="columnClasses()" ng-repeat="column in columns()" >
<div class="card" ng-repeat="result in getColumn(feed.results, column)" ng-show="feed.results.length > 0">
<div class="item item-image">
<a>
<img ng-src="{{thumb(result.src)}}" ui-sref="attraction({attraction_id: result.id})" ng-click="resultClicked(result)">
</a>
</div>
<div class="item item-bottom-sect">
<div class="row">
<div class="col-75 col-wrap">
<a ui-sref="attraction({attraction_id: result.id})" ng-click="resultClicked(result)" class="item-title">{{result.title}}</a>
</div>
<div class="col-25 right col-wrap">
<span ng-click="resultPicked(result)">
<span class="ion-heart heart heart-selected" ng-show="attractionIsPicked(result.id)" class="heart-selected"></span>
<span class="ion-heart heart" ng-show="!attractionIsPicked(result.id)"></span>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</ion-list>
<ion-infinite-scroll
ng-if="!resultsLoaded"
on-infinite="loadResults()"
distance="10%">
</ion-infinite-scroll>
</ion-content>
</ion-view>
Now, in my feed, there are two called to resultClicked() and one to resultPicked(). resultClicked(result) will return results just fine - but resultPicked(results) will always gets a null value! Also, thumb(result.src) always gets a null value. I have absolutely ZERO idea what - this is just things I'm confirming from console.logs. Is there anything glaringly wrong with the code?
Edit:
Here is a picture displaying what I am talking about. The cards are all "broken links" because the value im getting back is null (undefined) as shown in console. The "results" are also null, as shown in the console, when called from resultPicked(), but not from resultClicked().

Angular function inside JavaScript function

I have defined an AngularJS dialog as follows in my angular-app.js:
angular.module('myAPP', ['ngMaterial']).controller('AppCtrl', function($scope, $mdDialog) {
$scope.status = ' ';
$scope.showAdvanced = function(ev,_url) {
$mdDialog.show({
controller: DialogController,
templateUrl: _url,
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true
}).then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
});
function DialogController($scope, $mdDialog) {
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
}
And in my HTML page I have this:
<a ng-click="openDetailDialog()">Show details</a>
<script type="text/javascript">
function openDetailDialog(id) {
var id = getValue(id, 'id');
showAdvanced($event,'${readDetailURL}&id=' + id + '/');
}
</script>
The problem is that when I add the function showAdvanced() inside another function, it doesn't work.
When I call this function directly in ng-click, it works.
This works:
<a ng-click="showAdvanced($event,'http:myurl/test/id');">Show details</a>
Why?
First you can't attach or bind something that is not on the $scope, or the controller itself.
<a ng-click="openDetailDialog()">Show details</a>
That's wrong.
And second you can't access variables attached to the scope from plain javascript, 2WDB (two way data binding) just include HTML. And of course angular works with encapsulated scope.
The function ´showAdvanced()actually is part of the$scope`element. When you do this in your html:
<a ng-click="showAdvanced()">text</a>
AngularJs changes that (behind the scenes) to $scope.showAdvanced()
If you want to call it from javascript, you could try and change your function call to
`$scope.showAdvanced()`

Angular ng-init function loaded after directive

THE SITUATION:
Hello guys! I have an app where is possible to upload file. In the file page, if the file is a pdf file, the app display a little preview of the file.
I am using this very useful directive: angular-pdf-viewer
If i hardcode the path into a scope variable initialized in the controller everything works smoothly.
But of course i have to get some file info that i need for the path.
To do that i have a function that I call with ng-init.
The path is taken properly but the problem is that come too late..
In the console first i see the error message coming from the directive (because it does not find the file) and THEN, right after the error message, i see a console test message coming from the function.
That means that the path is loaded too late and not found by the directive
THE ERROR MESSAGE:
Error: Invalid parameter object: need either .data, .range or .url
THE DIRECTIVE:
app.directive('myPdfViewerToolbar', [
'pdfDelegate',
function(pdfDelegate) {
return {
restrict: 'E',
template:
'<div class="clearfix mb2 white bg-blue">' +
'<div class="left">' +
'<a href=""' +
'ng-click="prev()"' +
'class="button py2 m0 button-nav-dark">Back' +
'</a>' +
'<a href=""' +
'ng-click="next()"' +
'class="button py2 m0 button-nav-dark">Next' +
'</a>' +
'<span class="px1">Page</span> ' +
'<input type="text" class="field-dark" ' +
'min=1 ng-model="currentPage" ng-change="goToPage()" ' +
'style="width: 10%"> ' +
' / {{pageCount}}' +
'</div>' +
'</div>',
scope:
{
pageCount: '='
},
link: function(scope, element, attrs) {
var id = attrs.delegateHandle;
scope.currentPage = 1;
scope.prev = function() {
pdfDelegate
.$getByHandle(id)
.prev();
updateCurrentPage();
};
scope.next = function() {
pdfDelegate
.$getByHandle(id)
.next();
updateCurrentPage();
};
scope.goToPage = function() {
pdfDelegate
.$getByHandle(id)
.goToPage(scope.currentPage);
};
var updateCurrentPage = function() {
scope.currentPage = pdfDelegate
.$getByHandle(id)
.getCurrentPage();
};
}
};
}]);
THE VIEW:
<h2>File preview</h2>
<my-pdf-viewer-toolbar
delegate-handle="my-pdf-container">
</my-pdf-viewer-toolbar>
<pdf-viewer
delegate-handle="my-pdf-container"
url="file_url"
scale="1"
show-toolbar="false">
</pdf-viewer>
THE FUNCTION:
$scope.get_file_path = function()
{
var deferred = $q.defer();
$http({
method: 'POST',
url: base_url + 'api/get_file_detail/' + $stateParams.file_id
})
.success( function( data, status, headers, config )
{
deferred.resolve( data );
$scope.file_url = base_url + 'data/localhost/drawer/' + data.data_id + '/' + data.filename;
console.log($scope.file_url);
})
.error( function( data, status, headers, config )
{
deferred.reject( data );
});
}
THE QUESTION:
There another way to load the function before?
Or, how can i pass the file path to the directive?
Thank you very much!
Ok there is an easy solution: Wrap the directive inside an ng-if, in this way the directive is loaded only after the path has been initialized.
<div ng-if="file_url">
<pdf-viewer
delegate-handle="my-pdf-container"
url="file_url"
scale="1"
show-toolbar="false">
</div>

How to append/display/render data to page on click

I want to get the data from the API and display it on my index.html page. What's the best way in doing this? looking for multiple ways, that be jquery or data binding with angular. I can't seem to figure out a function to display the data I get. I'm fetching two different datas from two different players and I want to display them side by side. JSON data is returned by the API
/**Part of Index.html**/
<body ng-app="lolvs" ng-controller="MainController">
<div class="throwdown">
<h1> LoL THROWDOWN </h1>
<div class="summonerNames">
<input id="summonerOne" ng-model="summonerOne" placeholder="summoner name">
<button class="start" ng-click="start()">vs</button>
<input id="summonerTwo" ng-model="summonerTwo" placeholder="summoner name">
</div>
/**app.js**/
(function(){
'use-strict'
var mainCtrl = function mainCtrl($scope, $rootScope, MainFactory) {
$scope.start = MainFactory.start;
$rootScope.$on('gotStats', function (e, m) {
console.log('arguments >>', arguments);
$scope.player1 = {
totalChampionKills : 0,
totalDeathsPerSession : 0,
totalAssists : 0,
totalSessionsWon : 0,
totalSessionsLost :0,
totalMinionKills: 0,
totalTurretsKilled: 0,
};
$scope.apply();
});
};
var mainFactory = function ($http, $rootScope) {
var api = 'api_key=***************************';
var add = function(data, status, headers) {
var stats = {
totalChampionKills : 0,
totalDeathsPerSession : 0,
totalAssists : 0,
totalSessionsWon : 0,
totalSessionsLost :0,
totalMinionKills: 0,
totalTurretsKilled: 0,
};
var champions = data.champions;
for(var i = 0; i < champions.length; i++) {
var champ = champions[i].stats;
for(stat in stats) {
if(champ[stat]) {
stats[stat] += champ[stat]
}
}
}
};
var start = function(name) {
var options = {
url: 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' + name + '?' + api,
type: 'GET',
success: summonerOption
};
$http(options);
};
var summonerOption = function(data, status, headers) {
var name = Object.keys(data)[0];
var newOption = {
url: 'https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/' + data[name].id + '/ranked?season=SEASON4&' + api,
type: 'GET',
success: add
};
$http(newOption);
};
return {
start: start
}
};
angular.module('lolvs', [])
.controller('MainController', ['$scope', '$rootScope', 'MainFactory', mainCtrl])
.factory('MainFactory', ['$http', '$rootScope', mainFactory])
})();
What kind of data is being returned? If it is a json array, you might want to iterate through it before printing the whole thing to your webpage.
In theory however, you should handle the data after a successful ajax call, which seems to be executed after pressing the <button> in your index.html..
This could look like so:
var newOption = {
url: 'https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/' + data[name].id + '/ranked?season=SEASON4&' + api,
type: 'GET',
success: function(data) {
$('.containerForData').html('<div class="data-wrap">' + data + '</div>');
}
};
Unfortunately your question is not very clear, but I hope this helps.

Angular Controller Loading Before Data Is Loaded

I am writing a simple app that loads movie info from an API. After this loading, I am attempting to use Angular to display the movies in a simple list view. I am correctly loading the movies, but it seems like the angular controller is created and sends the movie array to the view before the movie array is populated. I am unsure how to get around this.
var movieList = [];
var app = angular.module('top250', []);
// immediately make a call to the server to get data (array of movies from text file)
$.post('/', {}, function(data) {
init(data);
});
app.controller('MovieController', function() {
// should be setting this.movies to an array of 250 movies
this.movies = movieList;
});
function init(data) {
// cycle through array, use title to retrieve movie object, add to array to be sent to view
$.each(data, function(index, value) {
var title = value.split(' (')[0];
title = title.split(' ').join('+');
var url = 'http://www.omdbapi.com/?t=' + title + '&y=&plot=short&r=json';
$.getJSON(url, function(data) {
console.log('in get json', data);
var movieObj = data;
storeMovie(movieObj);
});
});
}
function storeMovie(movieObj) {
movieList.push(movieObj);
}
And my HTML (although I'm certain this isn't the problem:
<body ng-controller="MovieController as MovieDB">
<div class="row">
<div class="large-12 columns">
<h1>IMDB Top 250 List</h1>
</div>
</div>
<div class="row">
<div class="large-12 columns" id="movie-list">
<div class="list-group-item" ng-repeat="movie in MovieDB.movies">
<h3>{{movie.Title}} <em class="pull-right">{{movie.Plot}}</em></h3>
</div>
</div>
<script src="js/foundation.min.js"></script>
<script>
$(document).foundation();
</script>
</body>
First I transformed your ajax calls to an angular factory:
app.factory('MoviesService', function($http, $q) {
function getMovie(value) {
var title = value.split(' (')[0];
title = title.split(' ').join('+');
var url = 'http://www.omdbapi.com/?t=' + title + '&y=&plot=short&r=json';
return $http.get(url).then(function(res){ return res.data; });
}
return $http.post('/').then(function(res) {
return $q.all(res.data.map(getMovie));
});
});
Then I can consume it like so:
app.controller('MovieController', function(MoviesService) {
var self = this;
MoviesService.then(function(movies) {
self.movies = movies;
});
});
don't use jquery
use angular $http or $resource
using $http, you set scope var to the data inside promise, and life will be good
You need to wait for you init method to complete:
function init(data, complete) {
$.each(data, function(index, value) {
var title = value.split(' (')[0];
title = title.split(' ').join('+');
var url = 'http://www.omdbapi.com/?t=' + title + '&y=&plot=short&r=json';
$.getJSON(url, function(data) {
console.log('in get json', data);
var movieObj = data;
storeMovie(movieObj);
}).always(function(){ // count competed ajax calls,
// regardless if they succeed or fail
if(index === data.length -1)
complete(); // call callback when all calls are done
});
});
}
Now you can do this:
app.controller('MovieController', function() {
$.post('/', {}, function(data) {
init(data, function(){
this.movies = movieList;
});
});
});
Personally I would just keep the movieList inside of the init method and send it with the callback when you're done, but that's just a preference.

Categories

Resources