AngularJS fill dropdwon with promise - javascript

I need to fill dropdown on view load. But problem is that when i'm trying to fill dropdown it appears blank. I
Controller
app.controller('CurrencyCtrl', ['$scope', 'Currency', '$http', function ($scope, Currency) {
$scope.curencies = [];
Currency.get(function (response) {
angular.forEach(response, function (val, key) {
$scope.currencies.push(val);
});
});
View
<select class="form-control" name="country"
data-ng-model="curencies"
data-ng-options="option.name for option in curencies.value track by curencies.id">
</select>
Resourse
app.factory("Currency", function ($resource) {
return $resource("api/currencies", {}, {
get: {method: "GET", isArray: true}
});
});

Data Factory
var datafactory = angular.module('Currency', ['Currency']);
datafactory.factory('Currency', function ($http, $q) {
return {
//Get Data
getCurrency: function (Date) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'api/Send_Mail'
}).success(function (data) {
deferred.resolve(data);
}).error(function (response) {
deferred.reject(response);
});
return deferred.promise;
}
}
Inside Controller
$scope.loadstatus++;
Factory.getCurrency().then(function (data) {
$scope.loadstatus++;
//do something
}, function (err) {
$scope.loadstatus--;
alert("Error" + error);
});
You could use loadstatus to controller the page loading

Try this:
Controller
app.controller('CurrencyCtrl', ['$scope', 'Currency', '$http', function ($scope, Currency) {
$scope.curencies = Currency.get();
});
View
<select class="form-control" name="country"
data-ng-model="curencies"
data-ng-options="option.name for option in curencies track by curencies.id">
</select>
Resourse
app.factory("Currency", function($resource, $q) {
return {
get: function() {
var deferred = $q.defer();
$resource("api/currencies").get().$promise.then(function(response) {
var result = [];
angular.forEach(response, function(val, key) {
result.push(val);
});
deferred.resolve(result);
})
return deferred.promise;
}
};
});

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
}
});
}
}

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>

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;
};
}]);

Angular: Retrieve updated value in directive

I am filling my template named commentRecipe.html with data.
And i can call controller.add(1,2,'comment here') from inside the template.
The item gets updated in the db and returns my new result.
The Question is: How can i update ex mhRecipeId with the retrieved data.
var app = angular.module('myApp');
app.directive('mhCommentRecipe', ['$log', 'commentService', function ($log, commentService) {
var commentController = function () {
var that = this;
that.add = function (commentId, recipeId, commentText) {
if (recipeId && commentText.length > 0) {
var resultObj = commentService.add(commentId, recipeId, commentText);
}
};
}
return {
restrict: 'A',
templateUrl: '/app/templates/commentRecipe.html',
scope: {
mhRecipeId: '=',
mhCommentId: '=',
mhCommentText: '='
},
controller: commentController,
controllerAs: 'controller'
}
}]);
(function () {
app.factory('commentService', [
'$log', 'httpService', function ($log, httpService) {
var baseEndpointPath = '/myRecipes';
return {
add: function (commentId, recipeId, commentText) {
$log.debug(commentId, 'c');
var data = {
commentId,
recipeId,
commentText
}
var promise = httpService.post(baseEndpointPath + '/comment', data);
promise.then(function (response) {
// added
},
function (error) {
$log.error(error);
});
},
remove: function (commentId) {
if (commentId) {
var data = {
commentId,
recipeId,
commentText
}
data.commentId = commentId;
var promise = httpService.post(baseEndpointPath + '/removeComment', data);
promise.then(function (response) {
$log(response, 'removed response');
},
function (error) {
$log.error(error);
});
}
}
};
}
]);
})();
app.factory('httpService', ['$http', '$q',
function ($http, $q) {
return {
get: function (endpoint) {
var deferred = $q.defer();
$http.get(endpoint)
.success(function (response) {
deferred.resolve(response);
})
.error(function () {
deferred.reject('Failed to fetch response from endpoint');
});
return deferred.promise;
},
post: function (endpoint, data, config) {
var deferred = $q.defer();
$http.post(endpoint, data, config)
.success(function (response) {
deferred.resolve(response);
})
.error(function () {
deferred.reject('Failed to post data to endpoint');
});
return deferred.promise;
},
put: function (endpoint, data, config) {
var deferred = $q.defer();
$http.put(endpoint, data, config)
.success(function (response) {
deferred.resolve(response);
})
.error(function () {
deferred.reject('Failed to put data to endpoint');
});
return deferred.promise;
}
};
}]);
You place the values you want to send to the directive into a variable:
// in controller
that.mhRecipeId = whateverValueHere;
that.mhCommentId = whateverValueHere;
that.mhCommentText = 'comment text';
then on the directive in html you would put:
<mh-comment-recipe mh-recipe-id="controller.mhRecipeId" mh-comment-id="controller.mhCommentId" mh-comment-text="controller.mhCommentText"></mh-comment-recipe>
This will pass the variables into the directive for use.
Unless I misunderstood your question :)
Solved the issue and i am quite embarrassed to tell the solution!
In my view i just used ex: mhRecipeId when i should have used the controllers value.

Can't cancel $interval in factory

I wrote a factory to long-poll, with start and stop methods. However, I can't cancel the timer. Any ideas?
app.controller("AuthCtrl", function($scope, $http, $window, User, Poller) {
Poller.start(1, $scope.session.user.user_uuid, function(result) {
User.data.queues.montage_progress = result.field;
if (result.field == 100) {
Poller.stop(); //DOES NOT STOP (see below)
}
});
})
Here is the factory:
app.factory('Poller', function($http, $q, $interval, $window) {
var poll = this;
poll.timer = null;
poll.checkProgress = function(field, user_uuid) {
var deferred = $q.defer();
$http({
method: 'GET',
url: '/api/v1/poll/',
json: true,
params: {
field: field,
user_uuid: user_uuid
}
})
.success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject("Error checking poll");
});
return deferred.promise;
};
poll.start = function(url, user_uuid, callback) {
poll.timer = $interval(function() {
poll.checkProgress(url, user_uuid).then(function(result) {
console.log(result);
callback(result);
}, function(error) {
alert(error);
});
}, 2000);
};
poll.stop = function() {
$interval.cancel(poll.timer);
};
return poll;
});
EDIT:
Changed $window.clearInterval to $interval.cancel(poll.timer); as suggested below. But still can't cancel polling...
You should use the cancel method of $interval, not clearInterval
poll.stop = function() {
$interval.cancel(poll.timer):
};

Categories

Resources