So, after spending time on a 2 year old question, I'll put something in here.
$scope.apply()
is unnecessary, and probably would trigger an error saying that apply is already in progress. If you're doing it right, you should very rarely, or never call this function. It's main use would be if you use third party libraries, that angular couldn't watch for changes, or see what they do, and you need to trigger the digest cycle manually.
I would advise to initalize variables, so your controller would look like this (I've also extracted the http request to a service, and used then
to handle responses and errors, since .success()
have been deprecated):
function merchantService($http) {
function post() {
return $http.get('localhost');
//Just a dummy $http request, instead of yours.
//return $http.post(global.base_url + '/merchant/list');
}
/* this is rather implicit, but if you are doing a service like this,
you can keep the functions "private" and export an object, that
contains the functions you wish to make "public" */
return {
post: post
};
}
function merchantListController($scope, merchantService) {
/* Initialize the variable, so ng-show and ng-hide
have something to work with in the beginning
rather then just being undefined. */
$scope.message = false;
// call the post from the function
merchantService.post()
.then(function (response) {
/* The first then() will hold the response
if the request was OK */
console.log(response);
$scope.merchants = response.data;
/* Since this then() will be triggered on a successful request
we are safe to say $scope.message should now be true. */
$scope.message = true;
})
.then(function (error) {
// The second one is for the failed request.
console.error(error);
});
}
var app = angular.module('myApp', []);
app.controller('merchantListController', merchantListController);
app.factory('merchantService', merchantService);
You can find a working fiddle here: https://jsfiddle.net/vnjbzf3o/4/
$data.status === 'success'
? – Cassidy