angularjs function not invoking mvc controller method - angularjs

Hi I am trying to access my method through angularjs but when I click the button it hits the function but does not invoke the Controller actionresult but when I manually add the url in it then calls the method.
here is my angular code:
$http({ method: 'GET', url: '/Home/GetEmployeeList?=' + search }).
success(function (data, status, headers, config) {
$scope.customers = data;
}).
error(function (data, status, headers, config) {
alert('error');
});
}
and here is my controller:
public JsonResult GetEmployeeList(string search)
{
search = "Lourens";
List<Quotation> quote = new List<Quotation>();
using (SpecialHireEntities sp = new SpecialHireEntities())
{
var quotes = sp.Quotations.Where(x => x.ClientName == search).ToList();
return new JsonResult { Data = quotes, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}

the url in the first line of JS should be
$http({ method: 'GET', url: '/Home/GetEmployeeList?search=' + search }).
rather than
$http({ method: 'GET', url: '/Home/GetEmployeeList?=' + search }).
With the code you mentioned, MVC model binding would never be able to find value for variable 'search' thus the request would not be resolved ending in an exception

Related

AngularJS service with data from REST API

I'm starting to read about services in Angular and confused as to how to use them with $http.
I currently use $http to fetch data from my REST API like the code below;
$scope.getRestaurant = function () {
var baseUrl = 'http://api.example.com/web/restaurant/details/' + $scope.id;
$http({
method: 'get',
url: baseUrl,
headers: {'Content-Type': 'application/json'}
}).
success (function(data, status, headers, config){
if(data && !angular.isUndefined(data) ){
$scope.restaurant = data;
} else {
$scope.restaurant = [];
}
}).
error(function(data, status, headers, config) {
//$scope.messageFailure(data.message);
});
}
$scope.id is a value on my controller how can I turn this function into service and then access the data returned in my controller?
This is how you can create a factory or service that has a function which takes an argument, you can then pass $scope.id in your controller to that function.
So to start, create a factory:
app.factory('myFactory', function($http) {
var factory = {};
var _myfunction = function(id)
{
return $http.get('http://api.example.com/web/restaurant/details/'+id);
}
factory.myFunction = _myfunction;
return factory;
});
and then in your controller, you will have:
app.controller('myCtrl', function('myFactory'){
var x = $scope.id;
$scope.getRestaurant = function (x) {
myFactory.myFunction(x).success(function(data, status, headers, config){
//whatever...
}).error(function(){
// whatever....
})
};
});
Of course it's just a general idea, you need to tweak it to meet your exact needs.
You have to inject the service into the controller and talk to it through there.
Quick example:
Your service
app.service '$restaurants', ['$http', '$q', ($http, $q) ->
fetch: (id) ->
deferred = $q.defer()
config =
url: "//api.example.com/web/restaurant/details/#{id}"
method: 'GET'
headers: 'Content-Type': 'application/json'
dataType: 'json'
x = $http config
x.error (data, status) -> deferred reject data, status
x.success (response, status, headers, config) ->
deferred.resolve response
deferred.promise
Controller injects the service
app.controller 'GodClass', ['$restaurants', ($restaurants) ->
$scope.id = 1
$restaurants.fetch($scope.id).then (response) ->
console.log response
Very much simplified but it'll get you the results based on the ID that you pass to the service.

Why variable is not decremented?

In Angular JS controller there is variable:
$scope.currentCount = {
'subscribers' : 0
}
Also in HTML template:
<span>{{currentCount.subscribers}}</span>
When I call method in this controller, this variable is not decremented in template, why?
$scope.saveSubscriber = function (type, name) {
$scope.saveSubObj.type = type;
$http({
url: "/subscribe",
method: "POST",
data: $.param($scope.saveSubObj),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
$scope.currentCount.subscribers--;
}).error(function(data, status, headers, config) {
//TODO
});
}
Look at success AJAX response:
$scope.currentCount.subscribers--;
Are you sure it fired the success method? I just checked and got the correct result in my local testing.
Could you please put $scope.currentCount.subscribers--; inside the $http error() method as well? Let's check then whether it decreases or not.

Need to bind the click events using Angular JS

I am new in Angular JS. I have written a script that open a modal box. There are few buttons in that modal box on which I want to apply the click event.
Below I have mentioned my code:
angular.module("vss_shoppingcart_modal",["ui.bootstrap","dialogs","ngSanitize"]).controller("vss_shoppingcart_dialogService",function($scope,$dialogs,$sce){
$scope.init = function(){
dlg = $dialogs.create("/dialogs/whatsyourname.html","vssShoppingCartCTRL",{},{key: false,back: "static"});
};
}) // end dialogsServiceTest
.controller("vssShoppingCartCTRL",function($scope,$sce,$http,$modalInstance,data){
$http({
method: "GET",
url: "' . $url . '"
}).
success(function(data, status, headers, config) {
$scope.trustedHtml = $sce.trustAsHtml(data); // Apply the html to modal
});
$scope.cancel = function(){
$modalInstance.dismiss("canceled");
}; // end cancel
$scope.removeProduct = function(event){
$http({
method: "GET",
url: event.target.id
}).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
// or server returns response with an error status.
});
}; // End removeProduct
$scope.updateQuantity = function(event){
$http({
method: "POST",
url: "' . $this->getUrl('shoppingcartpopup/index/updateCart') . '",
data: { "product_id": event.target.id, "qty": "2", "update_cart_action":"update_qty"}
}).
success(function(data, status, headers, config) {
$http({
method: "GET",
url: "' . $url . '"
}).
success(function(data, status, headers, config) {
$scope.trustedHtml = $sce.trustAsHtml(data);
});
}).
error(function(data, status, headers, config) {
// or server returns response with an error status.
});
}; // End updateQuantity
}) // end whatsYourNameCtrl
.run(["$templateCache",function($templateCache){
$templateCache.put("/dialogs/whatsyourname.html","<div class='ngModal' ng-bind-html='trustedHtml'></div>");
}]);// end run / module
On page load, I have passed a static block to modal window then by ajax request, I have updated the content again.
I don't know how to apply ng-click event on button in my view file.
In view, I have a link button -
<a href="javascript:void(0);" class="dialog-titlebar-close" role="button" ng-bind="cancel()" ng-click="cancel()">
<span class="header_close_icon">close</span>
</a>
ng-click is not working on this link.

How can I track the start and end of a number of async processes with AngularJS?

I have a loading icon set up on my page that looks like this:
<div class="loading-mask"
data-ng-show="action != null">
<span>{{action}} ...</span>
</div>
When I set $scope.action to a message appears in the loading box.
When loading my page I have a number of different async processes that get data. For example I have:
getUserProfiles: function ($scope) {
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
and:
getSubjects: function ($scope) {
var url = '/api/Subject/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.subjects = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
How can I make it so that the first of these async processes causes a "Loading" message to appear and the last of the async process causes the loading box to not show any more. Note at this time I am not concerned about error messages. I just want the loading to not show when everything is completed.
To expand on what devmiles has said, but to handle the multiple asynchronous functions, you will want to set a loading flag on your first function to be called. I.e.:
getUserProfiles: function ($scope) {
$scope.loading = true;
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
And then you will want to wrap each of your asynchronous functions in a promise, like so:
getUserProfiles: function ($scope) {
var deferred = $q.defer();
$scope.loading = true;
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
deferred.resolve();
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
deferred.reject();
});
return deferred;
},
You can then call $q.all on all of your asynchronous functions, and the success callback of this will occur once all asynchronous functions have resolved:
$q.all([getUserProfiles, getSubjects]).then(function() {
$scope.loading = false;
}
This means once all of your functions have resolved, loading will be set to false.
NB: If you want to access the data of your callbacks, you can pass it in as a parameter of "deferred.resolve(x)", and then in your $q.all callback, it will be available as function(x) { do something with x }.
Hope this helps!
EDIT: Don't forget to pass in angular's promise service, $q, to the controller where your functions are.
Just set some boolean flag on when your controller is being instantiated and reset this flag in your success/error functions.
.controller('MyCtrl', function ( $scope ) {
$scope.isLoading = true;
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.subjects = data;
$scope.isLoading = false;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
$scope.isLoading = false;
});
});
Use ng-show with this flag to show your loading thingy.

angular $http in service, return

I have this in my factory
productsFactory.getOneProduct = function(){
$http({
method: 'GET',
url: '/api/products/' + $stateParams.productID
}).
success(function(data, status, headers, config){
console.log(data);
return data;
}).
error(function(data, status, headers, config){
});
}
This is my controller:
$scope.selectedProduct = ProductsFactory.getOneProduct();
console.log(data) outputs the data i want. But I get 'undefined' when I call it from controller. Guess it got something to do with returning from anonymous functions? Am I doing it wrong?
Your getOneProduct function does not return anything which means it implicitly returns undefined, hence the error.
$http returns a promise and you must return that promise from your function. So change your code to this:
productsFactory.getOneProduct = function(){
return $http({
method: 'GET',
url: '/api/products/' + $stateParams.productID
}).
success(function(data, status, headers, config){
console.log(data);
return data;
}).
error(function(data, status, headers, config){
});
}
Then in your controller:
productsFactory
.getOneProduct()
.then(response){});
You need to return the Promise that is returned from $http:
productsFactory.getOneProduct = function(){
return $http({
method: 'GET',
url: '/api/products/' + $stateParams.productID
});
}
And then in your controller:
productsFactory.getOneProduct().then(successFunction, errorFunction);
You could simplify your factory call further:
productsFactory.getOneProduct = function(){
return $http.get('/api/products/' + $stateParams.productID);
}

Resources