I am creating a single-page AngularJS web app. My app needs to be able to query a backend service to get some information about a user's state, and this state information needs to be available to the various pieces of the single-page app. I created a service to manage this functionality, but I'm having trouble hooking things up in a way that seems reasonable to me.
Initially, I had things set up like this...
<service.js>
...
var url = 'www.my-backend.com';
this.val = [
{
name: 'undefined',
isValid: false
}
];
$http.get(url, {})
.success (function (data) {
this.val = data;
})
.error (function () {
this.val = [
{
name: 'error',
isValid: false
}
];
});
...
And then in my controller...
<controller.js>
...
$scope.val = service.val
...
This didn't work though (val.name
was 'undefined'), presumably because service.val
was bound to the controller's $scope before the get
request had a chance to terminate. However, that does seem at odds with what I read here.
The next thing I did was this...
<service.js>
...
var url = 'www.my-backend.com';
this.valPromise = $http.get(url, {});
...
And then in my controller...
<controller.js>
...
$scope.val = [
{
name: 'undefined',
isValid: false
}
];
service.valPromise
.success (function (data) {
$scope.val = data;
})
.error (function () {
$scope.val = [
{
name: 'error',
isValid: false
}
];
});
...
This worked, but I didn't like it. I feel like that logic belongs in the service.
So the next thing I did was work through the various suggestions that I found here, although none of them seemed to have the desired effect. I also saw this, but it seems like overkill and not really applicable to my problem.
Ideally I'd really like to figure out how to get my first attempt working (tightly bind my service variable to my controller scope by reference), but if that's not something that can really be done within the Angular framework, I'm happy to use some kind of watch
behavior. Can anyone spot what I'm doing wrong or why my service variable isn't getting properly hooked up to my controller?