I'm new to angular. I'm using a controller to grab data from a factory that I've populated with an $http.get that connects to a REST api:
videoModule.factory('myFactory', function($http){
var factory = {};
factory.getStuff = function(success, error) {
return $http({method: 'GET', url: '/api/backup'});
};
factory.postStuff = function(stuff){
};
return factory;
});
Here is my controller code:
app.controller('myController', function($scope, $http, myFactory){
myFactory.getStuff().success(function(data, status, headers, config){
$scope.stuff = data;
console.log(data);
$scope.selectedStuff = function($scope, $http){
var selectedFile = data[0].File_Name;
var selectedDir = data[0].File_SubDir;
var pack = selectedDir + "/" + selectedFile;
console.log(pack);
var result = { File_Location: pack };
console.log(result);
$http.post('api/test', result).success(function(data, status, headers){
console.log("Selected Video Sent to /api/test");
});
};
}).
error(function(data, status, headers, config) {
console.log("ERROR", data, status);
});
});
The first two lines within .success(function()) work fine - they load JS objects that I can use to bind to my HTML. The next chunk of code works perfectly. My view has an "ng-click=selectedStuff()" binding. When that element is clicked, the module logs result, a JS object {File_Location: pack} to my console.
However, I run into trouble in the next three lines. When I try to POST this object to /api/test, I get an error message in my dev tools:
TypeError: Cannot read property 'post' of undefined at k.$scope.selectedVideo.
I'm having trouble figuring out why $http is coming across as undefined. Has anyone encountered this issue before?
that's because $scope.selectedStuff
is expecting two arguments ($scope, $http)
and
in ng-click=selectedStuff()
you are not sending any parameters leaving $http as undefined in the function.
You can remove the arguments from the function as they can be taken from global scope.
$scope.selectedStuff = function(){
var selectedFile = data[0].File_Name;
var selectedDir = data[0].File_SubDir;
var pack = selectedDir + "/" + selectedFile;
console.log(pack);
var result = { File_Location: pack };
console.log(result);
$http.post('api/test', result).success(function(data, status, headers){
console.log("Selected Video Sent to /api/test");
});
};
Also, I would suggest you to consider bringing $scope.selectedStuff
definition to outside the myFactory.getStuff() success callback.