Variable not defined : AngularJS - javascript

I'm pretty new to Angular JS, but I was making a service to get information from a JSON:
This is the service code:
var staffServices = angular.module('staffServices', ['ngResource']);
staffServices.factory('Staff', function($resource){
return $resource('/api/staff/1', {}, {
query: {method:'GET', params: {}, isArray:false}
});
});
Controller
staffApp.controller('StaffCtrl', function($scope, Staff) {
Staff.query(function(data) {
console.log(data);
$scope.staff = data;
console.log(staff);
});
However, when I run the app, I'm able to see the "data" as an Object but I'm not able to asign it to the scope variable, I get the following "Error: staff is not defined".
Thanks for all your answers !

Instead of
console.log(staff); // this prints the var staff, which is undefined
should be
console.log($scope.staff); // this prints the staff property of $scope

Related

How to access sub objects of an object returned by AngularJS data service inside controller

I have an angularjs data factory that makes a server call and sets the returned data in the factory returned object like this
angular.module('app').factory('DataService', function() {
// Returning object
return {
data: {},
isLoaded: false,
getData:getdata
};
function getData() {
var self = this;
//Some Ajax Call returns an 'dataObject'
self.data = dataObject; //dataObject has a few subObjects and list
}
});
Now inside my angularjs controller I am making call to the DataService.getData() to make ajax call and hence set the returned dataObject within factoryobject 'data'
and I have declared it in controller like this
appV.data = DataService.data;
If I try to print it on console or access like this
console.log(appVm.data), I am able to access it, but if I try to access any subObjects like Ex - appVm.data.property1 or appVm.data.subObject1.subObject1.property, it gives undefined.
Can someone please explain why this behavior is occuring ?
Thanks in Advance
It is just example:
app.factory("messageService", function($q){
return {
getMessage: function(){
return $q.when("Hello World!");
}
};
});
And now the routing configuration that will use the service in a resolve.
$routeProvider
.when("/news", {
templateUrl: "newsView.html",
controller: "newsController",
resolve: {
message: function(messageService){
return messageService.getMessage();
}
}
})
These link may help you:
Link 1,
Link 2

undefined is not a function using $resource [duplicate]

When trying to poll a custom method copies on an AngularJS Resource I get the following error at angular.js:10033: (The method copy works just fine.)
TypeError: undefined is not a function
at https://code.angularjs.org/1.3.0-beta.8/angular-resource.min.js:9:347
at Array.forEach (native)
at q (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:7:280)
at q.then.p.$resolved (https://code.angularjs.org/1.3.0-beta.8/angular-resource.min.js:9:329)
at J (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:101:5)
at J (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:101:5)
at https://code.angularjs.org/1.3.0-beta.8/angular.min.js:102:173
at g.$eval (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:113:138)
at g.$digest (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:110:215)
at g.$apply (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:113:468)
Angular.js 10016 - 10035:
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop,
hasApply = false;
// Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
// The reason behind this is that console.log has type "object" in IE8...
try {
hasApply = !!logFn.apply;
} catch (e) {}
if (hasApply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args); // This is line 10033 where the error gets thrown.
};
}
Simplified resource:
angular.module('vgm.content-pages')
.factory('ContentPage', function($resource, $http) {
return $resource('/api/content-page/:id', { id:'#page.id' }, {
copy: {
method: 'POST',
url: '/api/content-page/copy/:id'
},
copies: {
method: 'GET',
isArray: true,
url: '/api/content-page/copies/:id'
}
});
});
Simplified directive where I'm getting the error:
angular.module('vgm.genericForms')
.directive('vgmFormCopyPicker', function() {
return {
restrict: 'E',
replace: true,
templateUrl: '/static/common/generic-forms/widgets/view-copy-picker.html',
scope: {
resource: '=',
},
controller: function($scope, $element) {
$scope.pages = [];
$scope.loadCopies = function() {
$scope.resource.$copies()
.then(function(response) {
$scope.pages = response.data;
});
};
}
};
});
As soon as I run the loadCopies method, executing the line $scope.resource.$copies() throws the error above.
In the Chrome Inspector I see the call to my API is actually being done. But resolving the promise seems to throw some error...
How can I solve this error?
EDIT:
$scope.resource = ContentPage.get({id: $stateParams.id}).$promise
$scope.resource.$save() // Works
$scope.resource.$update() // Works
$scope.resource.$copy() // Works
$scope.resource.$copies() // Does not work!
Angular Resource is trying to overwrite my initial resource with an array of items. But the instance of Resource does not have a method push of course.
I found the answer:
A resource is supposed to represent the matched data object for the rest of its lifespan. If you want to fetch new data you should do so with a new object.
$scope.copies = ContentPage.copies()
The answer from Guido is correct but I didn't get it at the first time.
If you add a custom method to your Angular $resource and using isArray: true and expecting to get an Array of something from your WebService you probably want to store the response in an Array.
Therefore you shouldn't use the instance method like this:
var ap = new Ansprechpartner();
$scope.nameDuplicates = ap.$searchByName(...);
But use the resource directly:
$scope.nameDuplicates = Ansprechpartner.searchByName(...)
Using following Angular resource:
mod.factory('Ansprechpartner', ['$resource',
function ($resource) {
return $resource('/api/Ansprechpartner/:id',
{ id: '#ID' },
{
"update": { method: "PUT" },
"searchByName": { method: "GET", url: "/api/Ansprechpartner/searchByName/:name", isArray: true }
}
);
}
]);
I am using Mean.js and this plagued for a few hours. There is a built in $update but it was not working when I tried to apply it to an object returned by a $resource. In order to make it work I had to change how I was calling the resource to update it.
For example, with a Student module, I was returning it with a $resource into $scope.student. When I tried to update student.$update was returning this error. By modifying the call to be Students.update() it fixed the problem.
$scope.update = function() {
var student = $scope.student;
var result = Students.update(student);
if(result){
$scope.message = 'Success';
} else {
$scope.error =
'Sorry, something went wrong.';
}
};

TypeError: undefined is not a function in Angular Resource

When trying to poll a custom method copies on an AngularJS Resource I get the following error at angular.js:10033: (The method copy works just fine.)
TypeError: undefined is not a function
at https://code.angularjs.org/1.3.0-beta.8/angular-resource.min.js:9:347
at Array.forEach (native)
at q (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:7:280)
at q.then.p.$resolved (https://code.angularjs.org/1.3.0-beta.8/angular-resource.min.js:9:329)
at J (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:101:5)
at J (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:101:5)
at https://code.angularjs.org/1.3.0-beta.8/angular.min.js:102:173
at g.$eval (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:113:138)
at g.$digest (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:110:215)
at g.$apply (https://code.angularjs.org/1.3.0-beta.8/angular.min.js:113:468)
Angular.js 10016 - 10035:
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop,
hasApply = false;
// Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
// The reason behind this is that console.log has type "object" in IE8...
try {
hasApply = !!logFn.apply;
} catch (e) {}
if (hasApply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args); // This is line 10033 where the error gets thrown.
};
}
Simplified resource:
angular.module('vgm.content-pages')
.factory('ContentPage', function($resource, $http) {
return $resource('/api/content-page/:id', { id:'#page.id' }, {
copy: {
method: 'POST',
url: '/api/content-page/copy/:id'
},
copies: {
method: 'GET',
isArray: true,
url: '/api/content-page/copies/:id'
}
});
});
Simplified directive where I'm getting the error:
angular.module('vgm.genericForms')
.directive('vgmFormCopyPicker', function() {
return {
restrict: 'E',
replace: true,
templateUrl: '/static/common/generic-forms/widgets/view-copy-picker.html',
scope: {
resource: '=',
},
controller: function($scope, $element) {
$scope.pages = [];
$scope.loadCopies = function() {
$scope.resource.$copies()
.then(function(response) {
$scope.pages = response.data;
});
};
}
};
});
As soon as I run the loadCopies method, executing the line $scope.resource.$copies() throws the error above.
In the Chrome Inspector I see the call to my API is actually being done. But resolving the promise seems to throw some error...
How can I solve this error?
EDIT:
$scope.resource = ContentPage.get({id: $stateParams.id}).$promise
$scope.resource.$save() // Works
$scope.resource.$update() // Works
$scope.resource.$copy() // Works
$scope.resource.$copies() // Does not work!
Angular Resource is trying to overwrite my initial resource with an array of items. But the instance of Resource does not have a method push of course.
I found the answer:
A resource is supposed to represent the matched data object for the rest of its lifespan. If you want to fetch new data you should do so with a new object.
$scope.copies = ContentPage.copies()
The answer from Guido is correct but I didn't get it at the first time.
If you add a custom method to your Angular $resource and using isArray: true and expecting to get an Array of something from your WebService you probably want to store the response in an Array.
Therefore you shouldn't use the instance method like this:
var ap = new Ansprechpartner();
$scope.nameDuplicates = ap.$searchByName(...);
But use the resource directly:
$scope.nameDuplicates = Ansprechpartner.searchByName(...)
Using following Angular resource:
mod.factory('Ansprechpartner', ['$resource',
function ($resource) {
return $resource('/api/Ansprechpartner/:id',
{ id: '#ID' },
{
"update": { method: "PUT" },
"searchByName": { method: "GET", url: "/api/Ansprechpartner/searchByName/:name", isArray: true }
}
);
}
]);
I am using Mean.js and this plagued for a few hours. There is a built in $update but it was not working when I tried to apply it to an object returned by a $resource. In order to make it work I had to change how I was calling the resource to update it.
For example, with a Student module, I was returning it with a $resource into $scope.student. When I tried to update student.$update was returning this error. By modifying the call to be Students.update() it fixed the problem.
$scope.update = function() {
var student = $scope.student;
var result = Students.update(student);
if(result){
$scope.message = 'Success';
} else {
$scope.error =
'Sorry, something went wrong.';
}
};

$scope inside a callback of a resource get call will not work

i am having a problem accessing the $scope. as it seems it is not working for me.
i have a resource:
squashApp.factory('CourtsService', function($resource) {
return $resource('/api/court/:num', {num: '#num'});
});
and my controller does:
squashApp.controller('CourtsController',
function CourtsController($scope, $window, $http, CourtsService) {
CourtsService.get({num:1}, function(data){
$scope.courts = data;
})
});
my server succeeds in returing a data which is in format of javascript object (JSON).
i have checked it. but for some reason the $scope is not updated and after this callback my view is not changing at all.
help please
I created a demo for you and your code looks ok.
However, it is always good to add some logic for the callback when the error occurs like this, so your app will not die silently.
squashApp.controller('CourtsController', function CourtsController($scope, $window, $http, CourtsService) {
CourtsService.get({
num: 1
}, function (data) {
console.log('success');
$scope.courts = data;
}, function (data) { // -> error handling
console.log('failed');
$scope.courts = data;
})
});
Demo
A simple way to access your $scope using angular $resource by using $promise (recommended)
squashApp.controller('CourtsController',
function CourtsController($scope,CourtsService) {
CourtsService.get({num:1}).$promise.then(function(data){
//$scope -- can be accessed here
}, function(failed){
}
});

Using AngularJS $resource to get data

I am trying to use $resource to get data from a static json file and here is the code snippet :
angular.module('app.services', ['ngResource']).
factory('profilelist',function($resource){
return $resource('services/profiles/profilelist.json',{},{
query:{method:'GET'}
});
});
In the controller,
function ProfileCtrl($scope,profilelist) {
$scope.items = [];
$scope.profileslist = profilelist.query();
for (var i=0;i<=$scope.profileslist.length;i++){
if($scope.profileslist[i] && $scope.profileslist[i].profileid){
var temp_profile = $scope.profileslist[i].profileid;
}
$scope.items.push(temp_profile);
}
But now, I am facing an error :
TypeError: Object #<Resource> has no method 'push'
Could you please help me where I am going wrong ?
You don't need to specify actions parameter for default $resource methods (these are 'get', 'save', 'query', 'remove', 'delete'). In this case you can use .query() method as is (this requires only service definition to be chaged):
angular.module('app.services', ['ngResource']).
factory('profilelist',function($resource){
return $resource('services/profiles/profilelist.json');
});
P.S. And one more hint is that your example unwrapped json into hash rather then array (that's why you received no push method error), if you need it to be an array set isArray: true to action config:
'query': {method:'GET', isArray:true}
And as #finishingmove spotted you really can't assign $resource result to obtain immediately, provide callback:
$scope.profileslist = profilelist.query(function (response) {
angular.forEach(response, function (item) {
if (item.profileid) {
$scope.items.push(item.profileid);
}
});
});

Categories