how to get data from controller to $scope in mvc using angularjs - javascript

I am new to angular js, I am using angular js with mvc5 application. I have created a module and controller in the js for angular. I have one action "View" in customer controller(MVC5). We need to show the all the customer in this view and i want to use "ng-repeat" here.
My problem is i am getting collection of customer as model, previously i was making foreach loop of model to show the customers. Now how i can add model into $scope data container so that i can use in ng-repeat.

What you have been doing till now is rendering the customers collection on server straight to the HTML returned to the client. What you want to do ideally is to render the HTML without the customers collection and have a call over $http service to your API controller to give you the data. From there is is easy, you
I suggest reading:
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
https://docs.angularjs.org/api/ng/service/$http
https://docs.angularjs.org/api/ng/directive/ngRepeat
Using $http in your controllers is far away from the best practice, but for simplification...the $http call in your controller could look like this:
$http({method: 'GET', url: '/api/customers'}).
success(function(data, status, headers, config) {
$scope.customers = data;
}).
error(function(data, status, headers, config) {
alert('error');
});
Then you ngRepeat in the view:
<ul>
<li ng-repeat="customer in customers">
{{customer.name}}
</li>
</ul>

For getting the data you need the http module to make call to server
https://docs.angularjs.org/api/ng/service/$http

you should be doing this via an api request to an MVC controller function that is returning json to your frontend and than use the data with $http or $resource to feed it into your controller.

Related

Failing to show an individual entry from an API in Angular

I'm building my first little AngularJS app.
I'm successfully able to show all entries from the API on the home page of the app.
Then I'm routing the user via ng-href to /jobs/{{job.id}} and have the appropriate controller to do that.
My console.log statement is telling me that the correct entry is being loaded via the GET request method but the template isn't actually pulling that back for display.
Here's the extent of what I have so far http://plnkr.co/QPW3lsLHfPxyYOKcVOKY (obviously my API isn't public) but wondering if there's something obvious I'm missing in my show template relating to the showController perhaps?
I've been working along with CodeSchool but I've had to make some mods to their code (for example the showController wasn't correctly defining $http or $routeParams).
Help appreciated.
So it seems there's an issue between the tutorial version of Angular 1.3.x and the one I'm using 1.4.x
However, using this works as sweet as a nut, passing $scope as a function parameter
angular.module('JobStore')
.controller('JobsShowController', function($http, $routeParams, $scope) {
$http({
method: 'GET',
url: '/jobs/' + $routeParams.id + '.json'
}).success(function(data) {
$scope.job = data;
console.log(data);
});
})

Problems getting data using AngularJS

I'm just learning Angular JS.
I'm trying to populate the scope variable with the result of an ajax database call.
The ajax call returns a propper json object(an array) but I cannot get $scope.contentType to output on my HTML page.
Can anyone see any reason this should not work?
app.controller('MainController', ['$scope', function($scope){
var allMyData;
$scope.title = 'Content Types List';
var request = $.ajax({
type: "POST",
dataType: "json",
url: "/angularJS/dbServices.cfc?method=getContentTypes"
})
request.done(function(data){
allMyData = data.DATA;
console.log(allMyData);
$scope.contentTypes = allMyData;
})
request.fail(function(){
console.log('fail');
})
}])
The reason your $scope isn't updating on the view is because you are changing that value outside the $digest cycle. You need to use AngularJS' built-in $http service.
You can get more information/documentation in the link above.
It is because you are using jQuery ajax which is not triggering angular digest. You can fix it with:
request.done(function(data){
$scope.apply(function() {
allMyData = data.DATA;
console.log(allMyData);
$scope.contentTypes = allMyData;
})
})
However, this is not the best practice. Instead you should 1) use $http service as mentioned in other answer 2) Move the entire logic to a separate service 3) use a high-level interface provided by ngResource

AngularJS and serverside filter and pagination

I'm looking to use Angular JS with WebAPI - will be returning a large number of results from the WebAPI and so want to use some sort of server-side pagination and filtering.
Most of the tutorials i've seen are for client side filtering which isn't what i'm looking for.
Not really used AngularJS before, so looking for a simple example which can show how to utilise this - effectively i have a list of products and want to be able to for example filter by price. As it's a large data set i'd want to utilise pagination as well.
At the moment, in my controller I have:
app.controller("MyController", function ($scope, $http){
$http.get('/api/ProductResults').
success(function (data, status, headers, config) {
$scope.results = data.results;
}).
error(function (data, status, headers, config) {
// log error
});
which will return a list of products and i will use to output a list.
The WebAPI will take parameters for page number and filters etc. but i'm not sure how to implement this in the code.
$http.get('/api/Products?page=1&minPrice=10')
I'd expect that i would get the current page number and min price from the URL parameters?
For the page number and minPrice, you could have scope variables that hold that info for you. Let's say you have a data grid on the page that includes navigation for the several pages of data you have. In this case, I would have a $scope.pageNumber variable bound to that data grid navigation item. A click on next or previous changes the value of $scope.pageNumber and on you $http you would use that $scope.pageNumber when constructing your request URL. The same goes for minPrice.
You can add your parameters to your request like this:
$http({
url: "/api/Products",
method: "GET",
params: {page : 1, minPrice : 10}
});

Pass variables in AngularJS $http GET?

Is it possible to pass a variable to a server in AngularJS $http service GET? I want to be able to "GET" a certain number of items from the server, and in the request I want to specify the number.
Thanks.
Yes, just add it onto the url:
$http.get("/users?items=15").success(function(data) {
$scope.users = data;
});
Then in your python handler for /users get the value of items using self.request.get("items")

Angular JS from rs.send()

Im generating some html code with angular in it, lets say it look something like this
exports.someApi = function(req,res){
res.send('<p>some html {{ "ENTER-PASSWORD" | translate }} </p>');
}
and in my controller im doing this
$http({method: 'GET', url: '/someapi'}).
success(function(data, status, headers, config) {
console.log(data);
$('.testPrint').html(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
the problem is, I get resposne rigth, but angular code is not executed it print this in html
some html {{ "ENTER-PASSWORD" | translate }}
it should write some html enter password
How to do this?
This is not the way to go with Angular. Specifically, $(...).html(data) will set the data directly to DOM, bypassing Angular's compilation step. This step is where the "magic" happens" (i.e. in your case the {{...}} get bound to the model).
Some ways to do it:
Make a directive and use templateUrl: "/someapi". When the directive is to be displayed, Angular will load /someApi and compile it.
Use ng-include="'/someApi'" (note single quotes within double quotes; this is intentional). Maybe together with ng-if to hide the content when not wanted.
The ui-router provides advanced facilities for subview navigation that may suit your needs.
A must-read is this great answer.

Categories