Populate a table dynamically in Angular - javascript

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>

Related

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

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?

AngularJS function from service is being called twice

I'm having trouble running a function from a service, because it is being called twice.
I've noticed that most of the problems of this nature are because people tend to call their controller twice (one time in the router and another in the view with ng-controller). But I checked, and my controller is not being invoked twice. Also: only on function from the service is being called twice.
Here it is:
.factory('findingsService', ['$http', '$log', '$q', '$cookies', function ($http, $log, $q, $cookies) {
return {
// THIS FUNCTION IS WORKING FINE!
list_findings: function(examId) {
var defer = $q.defer();
var session_token = $cookies.get('ACCESS_TOKEN');
$http.get(WS + URI_FINDINGS, {
headers: {
'sessionToken': session_token,
'Content-Type': 'application/json'
},
params: {
'examId': examId
}
})
.then(function (response) {
defer.resolve(response.data);
})
.catch(function (data) {
defer.reject(data);
});
return defer.promise;
},
// THIS FUNCTION IS BEING CALLED TWICE
attach_findings_to_exam: function(examId, findingsObj) {
var defer = $q.defer();
var session_token = $cookies.get('ACCESS_TOKEN');
$http.post(WS + URI_FINDINGS, findingsObj, {
headers: {
'sessionToken': session_token,
'Content-Type': 'application/json'
},
params: {
'examId': examId
}
})
.then(function (response) {
defer.resolve(response.data);
})
.catch(function (data) {
defer.reject(data);
});
return defer.promise;
}
}
}])
Since it's the same service and only one function is being called twice, and think that discarding the controller issue is fine. Can it be something about the global configuration of the $http.post?

Angular Js Translation Partial Issue

I am binding translation.
The issue is , some object convert to translated value, while some like mentioned below didn't work. This issue happened only first time when I build project. On refresh it gets fine.
This is not happening to all html objects.
angular.module('App').factory('APILoader', ['localStorageService', '$http', '$q', function (localStorageService, $http, $q) {
var translationAPIUrl = "Translation/Get";
return function (options) {
var deferred = $q.defer();
$http.get(translationAPIUrl, { params: { id: culture } }).success(function (response) {
data = JSON.parse(response.data);
deferred.resolve(data);
}).error(function (data) {
deferred.reject(options.key);
});
return deferred.promise;
};
}]);
Html:
<b> {{('Heading' |translate)}}</b>
I got it.
The issue is with deferred,
It did not resolve properly and get return.
The Key line is:
deferred.promise.then(function () {});
Here is the fixed code:
angular.module('App').factory('APILoader', ['localStorageService', '$http', '$q', function (localStorageService, $http, $q) {
var translationAPIUrl = "Translation/Get";
return function (options) {
var deferred = $q.defer();
$http.get(translationAPIUrl, { params: { id: culture } }).success(function (response) {
data = JSON.parse(response.data);
deferred.resolve(data);
deferred.promise.then(function () {});
});
}).error(function (data) {
deferred.reject(options.key);
});
return deferred.promise;
};
}]);

AngularJs call controller function from factory

I'm trying a sample with angularJs where I'm trying to call a factory method and in the factory method, I'm doing an ajax callback to get result from database and in the success event of the ajax callback, I need to call a function in the controller to bind the result to the UI.
My Angular Code:
angular.module('myApp.controllers', [])
.controller('TasksListCtrl', ['$scope', '$rootScope', '$routeParams', 'Task',
function($scope, $rootScope, $routeParams, Task) {
debugger;
//factory call
Task.query({
MobileNumber: $routeParams.MobileNumber,
ClientCode: $routeParams.ClientCode
});
$rootScope.UserMobileNumber = $routeParams.MobileNumber;
$scope.BindTasksList = function(resultData) {
debugger;
$scope.Tasks = resultData;
$scope.$apply();
}
}
]);
My Angular Factory Code:
'use strict';
(function() {
function GetTasks(MobileNumber, ClientCode) {
debugger;
$.ajax({
url: '/api/TasksAPI/GetTasksList',
type: 'GET',
datatype: 'json',
data: {
'MobileNumber': MobileNumber,
'ClientCode': ClientCode
},
success: function(response) {
debugger;
$scope.BindTasksList(response);
},
error: function(xhr) {}
});
};
angular.module('myApp.DbScripts', [])
.factory('Task', [
function() {
return {
query: function(data) {
debugger;
GetTasks(data.MobileNumber, data.ClientCode);
}
}
}
]);
}());
My app.js Code:
'use strict';
angular.module('myApp', [
'ngTouch',
'ngRoute',
'ngAnimate',
'myApp.controllers',
'myApp.DbScripts'
]).
config(['$routeProvider',
function($routeProvider) {
debugger;
$routeProvider.when('/tasks/:MobileNumber/:ClientCode', {
templateUrl: 'partials/tasks-list.html',
controller: 'TasksListCtrl'
});
$routeProvider.when('/tasks/:taskId', {
templateUrl: 'partials/task-details.html',
controller: 'TaskDetailCtrl'
});
$routeProvider.when('/tasks/:taskId/status', {
templateUrl: 'partials/task-completion-details.html',
controller: 'TaskCompletionDetailCtrl'
});
$routeProvider.when('/tasks/:taskId/route', {
templateUrl: 'partials/route-details.html',
controller: 'RouteDetailCtrl'
});
$routeProvider.otherwise({
redirectTo: '/tasks'
});
}
]);
But, I'm unable to call the function in controller. I've also tried it with angular.element(document.getElementById('TasksListCtrl')).scope().BindTasksList(response). But even that's not working.
Can anyone please point out the mistake I'm doing?
How to send the $scope of the controller to the factory?
You can do this by leveraging the $http promises, in you factory, return the promise instead as follows
'use strict';
(function() {
function GetTasks(MobileNumber, ClientCode) {
};
angular.module('myApp.DbScripts', [])
.factory('Task', [
function($http) {
return {
query: function(data) {
return $http({
url: '/api/TasksAPI/GetTasksList',
method: 'GET',
params: {
'MobileNumber': data.MobileNumber,
'ClientCode': data.ClientCode
}
}).then(function(result) {
return result;
});
}
}
}
]);
}());
Then in your controller you can access the $http response object that is returned:
//factory call
Task.query({
MobileNumber: $routeParams.MobileNumber,
ClientCode: $routeParams.ClientCode
}).then(function(resp) {
// access $http resp here and attach to $scope.Tasks
});
If you can, I would advocate using $q along $http as well, so that you do not need to parse through the http response and get a nice little response data object back
plnk

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