With all the examples of services, factories, using $scope
, using Controller as, I'm getting a bit confused. I have a simple ng-if
expression that's returning undefined because the data to evaluate isn't ready yet:
<div ng-if="ctrl.AlreadyBoughtShoe('ShoeId')"> ... </div>
...
<script>
(function() {
var MyApp = angular.module("MyApp", []);
MyApp.controller("MyAppController", function($http, $timeout, ShoeService) {
var x = this
loadRemoteData();
function loadRemoteData() {
ShoeService.GetShoes().then(function(Shoes){
applyRemoteData(Shoes);
});
}
function applyRemoteData(Shoes) {
x.Shoes = Shoes;
}
// FAILS HERE - Get undefined on the array
x.AlreadyBoughtShoe = function(shoeId) {
for (var i = 0; i < x.Shoes.length; i++) {
// Do stuff
}
}
});
MyApp.service("ShoesService", function($http, $q){
return({
GetShoes: GetShoes
});
function GetShoes() {
var request = $http({
method: "GET",
url: /MyUrl",
cache: false,
headers: $myHeaders
});
return( request.then(handleSuccess, handleError));
}
function handleError( response ) {
if (!angular.isObject(response.data) || !response.data.message) {
return( $q.reject( "An unknown error occurred." ) );
}
return( $q.reject(response.data.message) );
}
function handleSuccess( response ) {
return( response.data );
}
});
})();
</script>
Also, if it's relevant, in this particular case it has nothing to do with shoes... and the data is a person object, and there's no ng-repeat
going on, so the ID for the "shoe" is manually typed in. I jumbled up my actual code to simplify this so I can understand the best way to deal with it, but that ng-if
needs to evaluate after the data is ready to be evaluated.
I'm not sure how to best used promises or whatever else I need in this style of format, which I found an example of somewhere on the web a while back.