How to get $scope.someStuff response values into variable? - javascript

This is my angular controller:
angular
.module('hameedApp', [])
.controller('hameedController', function($scope, $http) {
$http({
method: 'GET',
url: 'json.php'
}).then(function(response) {
$scope.contacts = response.data;
}).catch(function(response) {
console.log('error');
})
});
This is my html from body tag:
<table class="table">
<tr>
<th>Name</th>
<th>Phone No</th>
<th>Email</th>
</tr>
<tr ng-repeat="contact in contacts">
<td>{{contact.name}}</td>
<td>{{contact.gsm}}</td>
<td>{{contact.email}}</td>
</tr>
</table>
<script>
var test = {{contacts}}
console.log(test);
</script>
I want to get above {{contacts}} full array json data in one variable called "test".
is it possible?

Angular concept is anything you put in $scope is not directly accessible in non-angular code. What you can do is, you can assign it to any global variable using window object like below.
angular
.module('hameedApp', [])
.controller('hameedController', function($scope, $http) {
$http({
method: 'GET',
url: 'json.php'
}).then(function(response) {
$scope.contacts = response.data;
window.contacts = response.data;
}).catch(function(response) {
console.log('error');
})
});
Now you can access that contacts anywhere in angular as well as non-angular code.
Edited
As you want to get the contacts in non-angular code, you have to use callback mechanism to tell your non-angular code about updated value. See below
In you <head>, add a new method in window like this
<head>
<script>
....
....
window.updateContacts = function(contacts) {
console.log(contacts);
}
....
....
</script>
</head>
Now you can use this callback from angular code, like below
angular
.module('hameedApp', [])
.controller('hameedController', function($scope, $http) {
$http({
method: 'GET',
url: 'json.php'
}).then(function(response) {
$scope.contacts = response.data;
window.updateContacts(response.data);
}).catch(function(response) {
console.log('error');
})
});

Related

How to pass data with Angularjs

How do i pass data from the controller to a component to show to the user?
app.js
(function(angular) {
'use strict';
angular.module('app', []).controller('MainCtrl', function MainCtrl($scope, $http) {
$http({
method: 'GET',
url: '/team',
}).then(function successCallback(response) {
console.log(response.data);
this.teams = response.data;
$scope.teams = response.data;
// var keys = Object.keys($scope.agendaEventData);
// $scope.eventslength = keys.length;
}, function errorCallback(response) {
});
}).config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);
})(window.angular);
component
(function(angular) {
'use strict';
angular.module('app').component('bringTeamToEvent', {
templateUrl: '/assets/ng/app/team/bringTeamToEvent.html',
bindings: {
teams: '<'
},
});
})(window.angular);
Template
{{$ctrl.teams}}
{{teams}}
The data is coming from the api no problems, i do not understand the complexity to get it to work.
Learning from https://docs.angularjs.org/tutorial/step_13
and https://docs.angularjs.org/guide/component#!
Setting the data on this.teams is correct, and correct to access it like $ctrl.teams. The issue here is that your $http callback functions are injecting their own function context so that this doesn't refer to the component.
For this reason, it's generally good practice to use arrow functions for callback functions:
$http({
method: 'GET',
url: '/team',
}).then(response => {
this.teams = response.data;
}, response => {
});
Here is a demo

Data from Angular .then function is not displayed on page

I have this code in my stucontrollers.j
/// <reference path="../angular.js" />
var stucontrollers = angular.module("stucontrollers", []);
stucontrollers.controller("GetStudentsList",
function GetStudentsList($scope, $http) {
$http({
method: 'GET',
url: '/api/students'
}).then(function(data) {
$scope.students = data;
});
});
and in my view, I have this
<div ng-app="StudentApp">
<div ng-controller="GetStudentsList">
<table>
<thead>
<tr>
<th>Id</th>
<th>FistName</th>
<th>LastName</th>
<th>Age</th>
<th>Gender </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in students">
<td>{{item.Id}}</td>
<td>{{item.FirstName}}</td>
<td>{{item.LastName}}</td>
<td>{{item.Age}}</td>
<td>{{item.Gender}}</td>
</tr>
</tbody>
</table>
</div>
</div>
and in my app.js this is what I have
/// <reference path="../angular.js" />
var module = angular.module("StudentApp", ["stucontrollers"]);
This is in my StudentsController.cs
// GET: api/Students
public IQueryable<Student> GetStudents()
{
return db.Students;
}
I am trying to get the list of the students into my view but I am only able to get it in the response of the page inspector not on the page itself. What am I doing wrong. Thank you.
EDIT
Now I am able to see my data in the console. But I still couldn't see it in my page. Below is the data I get in the console.
data
:
Array(2)
0
:
{Id: 1, FirstName: "Juan", LastName: "Dela Cruz", Age: 25, Gender: "Male"}
1
:
{Id: 2, FirstName: "Maria ", LastName: "Makiling", Age: 30, Gender: "Female"}
Try to call $scope.$apply() after setting the value.
$http({
method: 'GET',
url: '/api/students'
}).then(function(data) {
$scope.students = data;
$scope.$apply();
});
or simply
$http({
method: 'GET',
url: '/api/students'
}).then(function(data) {
$scope.$apply(function() {
$scope.students = data;
});
});
From the $apply documentation
$apply() is used to execute an expression in AngularJS from outside of the AngularJS framework.
To debug this, try setting value of $scope.students directly, like this:
/// <reference path="../angular.js" />
var stucontrollers = angular.module("stucontrollers", []);
stucontrollers.controller("GetStudentsList",
function GetStudentsList($scope, $http) {
$scope.students = [{Id: 1, FirstName: "John"}];
});
Then either one of two things happens:
a) You see John in the list: this means ng-controller and ng-repeat work. Problem in in fetching the data. Try next by console.logging your response.
b) You don't see John in the list: There is something wrong even before the request happens.
This worked for me, You might as well try it :
/// <reference path="../angular.js" />
var stucontrollers = angular.module("stucontrollers", []);
stucontrollers.controller("GetStudentsList",
function GetStudentsList($scope, $http,$rootScope) {
$http({
method: 'GET',
url: '/api/students'
}).then(function(data) {
$rootScope.$apply(function(){
$scope.students = data;
});
});
});
Try this:
/// <reference path="../angular.js" />
var stucontrollers = angular.module("stucontrollers", []);
stucontrollers.controller("GetStudentsList",
function GetStudentsList($scope, $http) {
$http({
method: 'GET',
url: '/api/students'
}).then(function(response) {
$scope.students = response.data;
});
});

Angularjs $scope.data not showing in html

I get the response from POST, it prints the data in the console but it doesn't show the data in the html page.
I have my controller, its just that the {{user}} doesnt show in html page
I can see the what it returns in the console,
angular.module('app.AllUsersCtrl', [])
.controller('AllUsersCtrl', function ($scope, $http, $cookies, $window, $state) {
$scope.getAccount = function (n) {
$http({
method: 'POST',
url: '/FYPapp/getAccount',
data: $.param({
username: n
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
}).success(function (data, status, headers, config) {
console.log(JSON.stringify(data));
$scope.user = JSON.stringify(data);
});
};
});
**Data Returns **
scripts.js:95 {"id":118,"firstname":"Lauren","lastname":"Smithss","description":"the Makup Chair the.....","enabled":true,"user":{"userid":21,"username":"theMak","email":"theMak22#mail.com","password":"995bf49114defd4f35d10e477135b89112ecdc2f25af6ab7969112842919ba4dc193b194f9485671","enabled":true},"followers":[],"username":"theMak"}
HTML: This is the html page
<link rel="stylesheet" type="text/css" href="static/app/css/css.scss">
<div class="mainDiv">
<h1> Profile Details</h1>
{{user}}
</div>
In your HTML you need to define our controller with ng-controller and also the ng-app which will be your module name.
Then you will need to make the data call.
After that you can directly assign the data to scope like this:
$scope.user = data;
As it appears you're using a controller alias, ie
.state('profile', {
url: "/profile",
templateUrl: '/views/profile.html',
controller: 'AllUsersCtrl',
controllerAs: 'allusers' // this one here
})
You should be assigning methods and properties to the controller instance, eg
.controller('AllUsersCtrl', ['$http', function($http) {
var ctrl = this;
this.getAccount = function(n) {
$http(...).then(function(response) {
ctrl.user = response.data;
});
};
}])
and in your template...
<img ng-click="allusers.getAccount(something)"...
and
<h1>Profile Details</h1>
<!-- for debugging -->
<pre>{{allusers.user | json}}</pre>
<!-- or for prod -->
<p>{{allusers.user.firstname}} {{allusers.user.lastname}}</p>
You are missing ng-controller in your html templates.
<h1> Profile Details</h1>
{{user}}

AngularJS: console.log does not display anything

I wrote a controller for login page. Here is my controller:
var authApp = angular.module('loginApp', [])
authApp.controller('LoginCtrl', ['$scope', '$location', 'loginFactory', function($scope, $location, loginFactory){
$scope.authenticate = function() {
loginFactory.login($scope.username, $scope.password)
.then(function(response) {
console.log(response.$statusText);
}, function errorCallBack(response) {
console.log(response.$statusText);
});
}
}]);
My service:
authApp.factory("loginFactory", function ($http) {
return{
login: function(username, password) {
var data = "username="+username+"&password="+password+"&submit=Login";
return $http({
method: 'POST',
url: 'http://localhost:8080/login',
data: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
});
}
When I debug the code, authentication seems successful and it did get into then function. However nothing displays in console. And I got a warning(?) saying undefined for the line console.log(response.$statusText);. It is not an error since it is not red. Why doesn't it print out anything?
Use response.statusText not response.$statusText. The documentation for AngularJS $http requests lists statusText as one of the properties of the response object - https://docs.angularjs.org/api/ng/service/$http

not getting data from $http from service to scope

we are trying to get data from service agrService with $http its working but when i reccive data to controller i am not able to access it outside that function
$scope.resource return data inside function but not outside please help.
var app = angular.module('app', ['ui.router','ngTasty']);
app.config(['$urlRouterProvider', '$stateProvider',function($urlRouterProvider, $stateProvider, $routeProvider, $locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/home.html',
controller: function($scope, $http, $location, agrService) {
agrService.bannerSlides().then(function(data) {
//its working here
$scope.resource = data;
}, function(error) {
// do something else
});
I NEED TO ACCCESS DATA HERE CAN ANY BODY HELP
console.log($scope.resource);
}
});
}]);
app.service('agrService', function($q, $http) {this.bannerSlides = function() {
var dataUrl = 'http://WWW.EXP.COM/codeIgniter_ver/main/home';
var ret = $q.defer();
$http({
method: 'GET',
dataType: "json",
url: dataUrl
})
.success(function(data, status, headers, config) {
ret.resolve(data);
}).error(function(data, status, headers, config) {
ret.reject("Niente, Nada, Caput");
});
return ret.promise;
};
});
My suggestion would be to rethink the logic a bit. You want to do something with the data after you receive it, so why not make a function that you call once the data is received?
You'll never be able to access the resource data in that console log, simply because $http is an async call, and no matter if you return a promise or not, it's simply not ready at that point.
However, if you use it in a template or elsewhere that uses angular's double binding, it will work just fine.
To fix your issue, you can define a function with what happens after that service call and simply call it from the success callback:
agrService.bannerSlides().then(function(data) {
//its working here
$scope.resource = data;
myAfterFunction(); // <--- here
}, function(error) {
// do something else
});
and the function can be:
function myAfterFunction() {
console.log($scope.resource);
}
And btw. your service is an example of deferred antipattern, you can simply do this:
app.service('agrService', function($q, $http) {this.bannerSlides = function() {
var dataUrl = 'http://WWW.EXP.COM/codeIgniter_ver/main/home';
return $http({
method: 'GET',
dataType: "json",
url: dataUrl
})
};
});

Categories