I want to use a scope variable $scope.field.name when a request is done or failed. I tried to console it but it says undefined. How can I access a scope variable inside these syntax?
usiApp.controller('fieldController',['$scope','$window','$http','field','$timeout','Profile','Referrence',function ($scope,$window,$http,field,$timeout,Profile,Referrence)
{
$scope.DoSomething = function(){
$scope.field.class = 'fieldController'; //class of php method
$scope.field.method = 'DoSomething'; //name of php method
$scope.field.name = 'Ellsworth';
field.getdata($scope.field)
.success(function(data){
if (data == true) {
console.log($scope.field.name); //returns error this is the problem
} else {
console.log($scope.field.name); //returns error
}
})
.error(function(data, status) {
$scope.messages = data || "Request failed";
$scope.status = status;
console.log($scope.status);
console.log($scope.messages);
console.log($scope.field.name); //returns error
});
}
}
My field.getdata service function:
usiServices.factory('field', function($http) {
return {
getdata : function(option) {
return $http({
method: 'POST',
url: 'php/field-route.php',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(option)
});
},
}
}
You missed $scope.field = {};
.The line will create an empty object. After creating the object, then you can create property of the object($scope.field.class, $scope.field.method,$scope.field.name
). As the object is not created, you are getting the undefined error.
Add this $scope.field = {};
line before the following:
$scope.field.class = 'fieldController'; //class of php method
$scope.field.method = 'DoSomething'; //name of php method
$scope.field.name = 'Ellsworth';
So, the final updated lines will be as follows:
$scope.field = {};
$scope.field.class = 'fieldController'; //class of php method
$scope.field.method = 'DoSomething'; //name of php method
$scope.field.name = 'Ellsworth';