why this $scope.$on doesn`t work? - javascript

Using angular, I wrote a test to get current user information. This is my code:
var app = angular.module('gzmu', ["ngRoute",'chart.js']);
app.run(function ($rootScope, $http) {
$http({
method: 'GET',
url: 'datacon/user_info.php',
}).success(function (response) {
//response is ready
$rootScope.$broadcast("userinfo", response[0]);
})
});
app.controller('data', function ($scope, $http, $rootScope) {
$scope.username='';
$scope.$on("userinfo",
function (event, msg) {
//this function not work every time,when i reload the page,no alert is pop out
if(msg){
$scope.username = msg.user;
console.log($scope.username)
alert($scope.usernamea)
}
else{
alert(msg);
}
});
});
If I want to ask if I want the $scope.username to be setup in $on, what should I do?

Related

How to implement angularjs async?

I am using AngularJS v1.5.8, My requirement is when i click the Next button it'll display 'Processing...' inside button as text before complete the operation, i have included the $q with my services to get the asynchronous facility, but not working. please see my below codes.
Service
mainApp.factory('PINVerificationServices', ['$http', '$rootScope','$q', function ($http, $rootScope) {
return {
IsPermitted: function (param) {
return $q($http({
url: '/Api/ApiPINVerification/IsPermitted/' + param,
method: 'POST',
async: true
}));
}
};
}]);
Controller
mainApp.controller('PINVerificationController', function ($scope, $rootScope, $state, $window,$q, PINVerificationServices) {
$scope.SubmitText = "Next";
$scope.Next = function () {
$scope.SubmitText = "Processing...";
PINVerificationServices.IsPermitted($scope.PIN).then(function (result) {
$scope.SubmitText = "Next";
});
}
}
HTML
<div class="list-group list-group-sm">
<div class="list-group-item">
<input class="form-control" ng-model="PIN" placeholder="PIN" required id="PIN" name="PIN" type="text" />
</div>
</div>
<button type="submit" ng-click="Next()">{{SubmitText}}</button>
Try this:
return $http({
method: 'POST',
url: '/Api/ApiPINVerification/IsPermitted/' + param
});
Make below changes (from your requirement of nested $http).
In factory Use only $http, and no need of $rootScope as well, It should be like :
mainApp.factory('PINVerificationServices', ['$http', function ($http) {
return {
IsPermitted: function (param) {
return $http({
url: '/Api/ApiPINVerification/IsPermitted/' + param,
method: 'POST'
});
},
GetStudentInformationByPIN : function () {
return $http({
url: '/Api/ApiPINVerification/GetStudentInformationByPIN /',//your api url
method: 'GET'
});
}
};
}]);
In controller make use of $q.all() :
mainApp.controller('PINVerificationController', function ($scope, $rootScope, $state, $window,$q, PINVerificationServices) {
$scope.SubmitText = "Next";
$scope.Next = function () {
$scope.SubmitText = "Processing...";
$q.all([PINVerificationServices.IsPermitted($scope.PIN),
PINVerificationServices.GetStudentInformationByPIN($scope.PI‌N),
//other promises
]).then(function (result) {
if(result[0].data){
$scope.SubmitText = "Next";
}
if(result[1].data){
// studentdata response handling
}
});
}
}

Angular JS assign scope variable after HTTP post request

I am not able to assign the scope variable after a HTTP post request.
controller:
storeApp.controller("formCtrl", ['$scope', '$http', function ($scope, $http) {
$scope.variableToBeAssigned= null;
}
$scope.formsubmit = function () {
$http.post($scope.url, { "name": $scope.name}).
success(function (data, status){
$scope.variableToBeAssigned= "success";
})}
The formsubmit() function is called when the user submits the form. The "variableToBeAssigned" remains null even after the HTTP Post request.
You should place the function inside the controller,
storeApp.controller("formCtrl", ['$scope', '$http', function ($scope, $http) {
$scope.variableToBeAssigned= null;
$scope.formsubmit = function () {
$http.post($scope.url, { "name": $scope.name}).
success(function (data, status){
$scope.variableToBeAssigned= "success";
return($scope.test1);
})}
}

Populate a table dynamically in Angular

I am new to Angular. I have created an app that, given the click of a button, should trigger a call that gets a set of json objects and populate a specific table. In the following controller code I have managed to populate the table directly without the click of a button (via the this.tableParams), but what I want is to trigger this data fetching process and populate the table only when the populateTable() function is called.How do I do it?
(function() {
'use strict';
angular
.module('anomalies')
.controller('controller', ['$log', '$scope', '$http', 'NgTableParams', function ($log, $scope, $http, NgTableParams) {
$scope.populateTable = function () {
//
}
this.tableParams = new NgTableParams({}, {
filterDelay: 300,
getData: function (params) {
return $http({
method: 'GET',
url: '/server/data.json'
}).then(function (response) {
return response.data;
}, function (response) {
$log.log(response);
return [];
});
}
});
}]);
})();
Why not creating the NgTableParams-object inside the populateTable-function?
angular
.module('anomalies')
.controller('controller', ['$log', '$scope', '$http', 'NgTableParams', function ($log, $scope, $http, NgTableParams) {
$scope.populateTable = function () {
this.tableParams = new NgTableParams({}, {
filterDelay: 300,
getData: function (params) {
return $http({
method: 'GET',
url: '/server/data.json'
}).then(function (response) {
return response.data;
}, function (response) {
$log.log(response);
return [];
});
}
});
}.bind(this);
}]);
Not the .bind(this). This ensures the this keyword means the same inside the populateTable-function as in the controller.
Move this.tableParams into the $scope.populateTable function. Bind this function to a button in the view e.g <button ng-click="populateTable()">Click Me!</button>

Angularjs Ajax get sending headers

I'm new to angularjs, and im using a service for my http requests.
one of the rest api's i need to send key value pairs in the header.
username: foo
password: bar
how do i do it using the http request format i have in my service. (i'm aware i need to pass an argument in the function i don't how to go about it and what object format)
.service('UserService', ['$http', '$rootScope', function ($http, $rootScope) {
this.CheckIfUserExists = function () {
return $http.get($rootScope.endPoint + '/user/email_token');
};
}
...
//in the controller
UserService.CheckIfUserExist()
.success(function (data) {
console.log(data);
//handler
}).
error(function(error) {
//handler
});
Example from the doc
you need know what kind of auth. you can use post for example.
.service('UserService', ['$http', '$rootScope', function ($http, $rootScope) {
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).success(function(){...}).error(function(){...});
In your case:
.service('UserService', ['$http', '$rootScope', function ($http, $rootScope) {
this.CheckIfUserExists = function () {
var req = {
method: 'POST',
url: 'http://example.com'
data: { 'username': 'foo', 'password': 'bar' }
};
return $http(req);
}
}

Angular get in controller

I am learning Angular. The following code works:
.controller('abc', function ($scope, $http)
{
$http.get("/Handlers/Authentication.ashx")
.success(function (data)
{
alert(data);
})
This function however does not:
.controller('abc', function ($scope, $http)
{
$scope.run = function ($scope, $http)
{
$http.get('/Handlers/Authentication.ashx');
// .success(function (data)
//{
// alert(data);
//});
};
}
I know that I should use a service here. But for learning purposes I would like to know why it does not work to call this function inside:
<body ng-app="MainModule">
<div ng-controller="abc">
<div>
<button type="button" class="btn btn-info" ng-click="run();">{{xx}}</button>
Thank you for help in advance
You're overriding controller injected $http service here :
$scope.run = function ($scope, $http)
{
$http.get('/Handlers/Authentication.ashx');
// .success(function (data)
//{
// alert(data);
//});
};
Just remove all arguments on your scope function and it should work :
.controller('abc', function ($scope, $http) {
$scope.run = function () {
$http.get('/Handlers/Authentication.ashx')
.success(function (data){
alert(data);
});
};
}
Because you are getting data, but don't doing with it something.
$http.get('/Handlers/Authentication.ashx').then(function(data){
console.log(data);
}, function(err){
console.log(err);
})

Categories

Resources