I have to add an AngularJs control to my cshtml file in a project but as I couldn't make it work I tried to create a simple test application, and now it seems that even this simple app (including only an app module and a controller) is not working!
app.js
(function() {
angular.module('testApp', []);
});
GetProductsCtrl.js
angular.module('testApp.controllers', []); //this is supposed to go in a separate file
angular.module('testApp.controllers')
.controller("GetProductsCtrl", function ($scope, $http) {
$scope.greetings = "hi";
$http({
method: 'GET',
url: "http://localhost:54327/api/products"
})
.success(function (data) {
$scope.products = data;
});
});
ProductsController.cs
public class ProductsController : ApiController
{//inside the web api project and running on http://localhost:54327/
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null)
return NotFound();
return Ok(product);
}
}
usage
<script src="~/Scripts/angular/common/GetProductsCtrl.js"></script>
<div class="row" ng-app="testApp">
<div>
Here I want to add the control.
{{1+1}} #*even this is not evaluated by angular!(it was working)*#
<ul ng-controller="GetProductsCtrl">
<li ng-repeat="product in products">
{{product.Name}} : $ {{product.Price}}
</li>
</ul>
</div>
</div>
and finally bundle:
bundles.Add(new ScriptBundle("~/bundles/angular").Include(
"~/Scripts/angular.min.js",
"~/Scripts/angular/app.js"
));
What I can guess is that Bundle will try rename your $http provider.
So try .controller("GetProductsCtrl", ["$scope", "$http", function ($scope, $http){
}] instead.
Related
I'm creating a small contacts application in AngularJS and want to retrieve data by calling a web service.
I created two projects in VS (one Website for the angularJS code and one Web Application for the web service code). I put them both under the same Solution.
This is my index.html markup:
<body ng-app="app" ng-controller="controller" ng-cloak>
<div class="header" ng-bind="header"></div>
<div class="content">
<!-- This content will switch -->
<ui-view></ui-view>
</div>...
My contacts.html markup, which goes inside ui-view tag:
<ul>
<li ng-repeat="c in contacts" >...
In JS I created the following service:
// Contacts Service
app.service("getContacts", function ($http, $q) {
// web-service path
var ws = "http://localhost:65123/";
var getContact = function () {
//create defer object
var contactsPromise = $q.defer();
$http.get(ws + "api/Contact")
.then(function (res) { contactsPromise.resolve(res);
}, function (err) { contactsPromise.reject(err); });
return contactsPromise.promise;
};
return
{ getContact: getContact }
});
and the following index Controller:
//index(root) Controller
app.controller("controller", function ($scope,getContacts) {
$scope.contacts = getContacts.getContact().then(function(res){ $scope.contacts = res; });
});
In my Web Application I created a single Model:
public class Contact
{
public string name;
public string phone;
public string mail;
public string address;
public static List<Contact> getContacts() {
// TODO retrieve Contacts from DB
List<Contact> c = new List<Contact>();
c.Add(new Contact() { name="aaaa", phone="111", mail="aaaa#gmail.com",address="sdsd"});
c.Add(new Contact() { name = "bbbb", phone = "222", mail = "b#g.com", address = "sss" });
c.Add(new Contact() { name = "cc", phone = "444", mail = "a#l.com", address = "ggg" });
return c;
}
And its Controller:
namespace WebApplication1.Controllers
{
public class ContactController : ApiController
{
// GET: api/Contact
public List<Contact> Get()
{
return Contact.getContacts();
}
}
}
When I run the whole project (both Angular and WS) I get an ERR_CONNECTION_REFUSED error.
What could be the problem here? Is something wrong with my ajax call using $http?
P.S. I allowed CORS in my Web Application.
the "getContacts" added as a dependency will return only a promise and not the list you want. It should look like this:
//index(root) Controller
app.controller("controller", function ($scope,getContacts) {
getContacts.then(function(contacts){ $scope.contacts = contacts; });
});
I hope this is the answer you're looking for!
I am trying to implement textbox autocomplete functionality in MVC angularjs. I have see examples with angucomplete method but it gets all db values in one shot. When I hit the key back again it doesnt go to MVC controller action.
Below is my code view code:
<div ng-controller="sampleController">
<div ng-app="medAapp" ng-controller="sampleController">
<div angucomplete-alt id="txtautocomplete" placeholder="Type Country name" pause="100" selected-object="AfterSelectedCoutries" local-data="countries" search-fields="Country" title-field="Country" minlength="1" input-class="form-control" match-class="highlight">
</div>
<div ng-show="SelectedCountries">
Selected Country: {{SelectedCountries.Country}}
</div>
</div>
</div>
Module code:
var medApp = angular.module("medApp", ['angucomplete-alt', 'ui.grid', 'ui.grid.pagination', 'ui.grid.selection', 'ui.grid.exporter',
'ui.grid.grouping', 'ui.grid.expandable']);
Angular Controller code:
medApp.controller("sampleController", ['$scope', '$http', function ($scope, $http) {
$scope.countries = [];
$scope.SelectedCountries = null;
$scope.AfterSelectedCoutries = function (selected) {
if (selected) {
$scope.SelectedCountries = selected.originalObject;
}
}
$http.get("/Home/GetCountry").then(function (d) {
$scope.countries = d.data;
}, function (error) {
alert('Failed');
})
}])
MVC Controller code:
public JsonResult Getcountry()
{
List<Item> listcountry = new List<Item>()
{
new Item()
{
Id=1,
Name= "Crocin"
},
new Item()
{
Id=2,
Name= "Bruffen"
}
};
return Json(listcountry, JsonRequestBehavior.AllowGet);
}
My question is GetCountry method should have a parameter to get the required records but in none of the samples it does.
Any suggestions??
Thanks
I am using Angular Routing with a webapi 2 controller.
Although the default path loads with the correct data, when I click on an item in a list containing a link to a details page, no data is loaded.
The browser shows what I believe to be the correct url (http://localhost:xxxxx/#/details/2) but the DetailsController script file is not called and no method on the webapi2 controller is called.
Here is my main page :
<div class="jumbotron">
<h1>Movies Example</h1>
</div>
#section scripts {
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/Client/Scripts/atTheMovies.js"></script>
<script src="~/Client/Scripts/ListController.js"></script>
<script src="~/Client/Scripts/DetailsController.js"></script>
}
<div ng-app="atTheMovies">
<ng-view></ng-view>
</div>
Here is the list partial :
<div ng-controller="ListController as ctrl">
<h1>{{ctrl.message}}</h1>
<h2>There are {{ctrl.movies.length}} Movies in the Database</h2>
<table>
<tr ng-repeat="movie in ctrl.movies">
<td>{{movie.Title}}</td>
<td>
<a ng-href="/#/details/{{movie.Id}}" >Details</a>
</td>
</tr>
</table>
</div>
Here is the details partial:
<div ng-controller="DetailsController as ctrl2">
<h2>ctrl2.message</h2>
<h2>{{movie.Title}}</h2>
<div>
Released in {{movie.ReleaseYear}}
</div>
<div>
{{movie.Runtime}} minutes long.
</div>
</div>
Here is the javascript file to create the angular app:
(function () {
var app = angular.module("atTheMovies", ["ngRoute"]);
var config = function ($routeProvider) {
$routeProvider
.when("/list", { templateUrl: "/client/views/list.html" })
.when("/details/:id", { templatUrl: "/client/views/details.html" })
.otherwise(
{ redirectTo: "/list" });
};
app.config(config);
}());
Here is the javascript file to create the list controller:
(function (app) {
app.controller("ListController", ['$http', function ($http) {
var ctrl = this;
ctrl.message = "Hello World!";
ctrl.movies = [];
$http.get("/api/movie")
.success(function (data) {
ctrl.movies = data;
})
.error(function(status){
ctrl.message = status;
});
}])
}(angular.module("atTheMovies")));
Here is the javascript file to create the details controller:
(function (app) {
app.controller("DetailsController", ['$routeParams', '$http', function ($routeParams, $http) {
var ctrl2 = this;
ctrl2.message = "";
ctrl2.movie = {};
var id = $routeParams.id;
$http.get("/api/movie/" + id)
.success(function(data){
ctrl2.movie = data;
}).error(function (status) {
ctrl2.message = status;
});
}])
}(angular.module("atTheMovies")));
Finally here is the webapi2 controller
public class MovieController : ApiController
{
private MovieDb db = new MovieDb();
// GET: api/Movie
public IQueryable<Movie> GetMovie()
{
return db.Movies;
}
// GET: api/Movie/5
[ResponseType(typeof(Movie))]
public IHttpActionResult GetMovie(int id)
{
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return NotFound();
}
return Ok(movie);
}
You have a typo in your route config i.e. templatUrl
.when("/details/:id", { templatUrl: "/client/views/details.html" })
should be
.when("/details/:id", { templateUrl: "/client/views/details.html" })
Being new to angular I'm stocked to figure out how to call a web service which should be parsed and maped via URL, like if the URL is getting called directly to get listed request with the given params
what I mean let say I have
/api/products -- calling all products(this is the access point)
/api/products/?page=2&orderby=asc -- calls products with pagination and orderby and here is what's bothering me because the api is getting called via ajax and there is no URL mapping of the target
My Codes
Html markup
<div ng-controller="MainCtrl">
<div class="row">
<div class="col-lg-7 col-md-7 col-sm-7">
<pagination total-items="totalItems" num-pages="totalPages" ng-model="currentPage" ng-change="selectPage(currentPage)" max-size="5" class="pagination-sm" boundary-links="true"></pagination>
</div>
<div ng-repeat="product in products"></div>
</div>
</div>
contoller
//called when navigate to another page in the pagination
$scope.selectPage = function(page) {
$scope.filterCriteria.pageNumber = page;
$scope.fetchResult();
};
//The function that is responsible of fetching the result from the server and setting the grid to the new result
$scope.fetchResult = function() {
return api.items.search($scope.filterCriteria).then(function(data) {
$scope.products = data;
$scope.totalPages = data.total;
$scope.productsCount = data.TotalItems;
}, function() {
$scope.products = [];
$scope.totalPages = 0;
$scope.productsCount = 0;
});
};
Service
.factory('api', function(Restangular) {
//api call to
return {
products: function() {
return Restangular.all('products').getList();
},
product: function(id) {
Restangular.one("products", id ).get().then(function(c) {
return c;
});
},
update: function(id) {
Restangular.one("products", id).put().then(function(c) {
return c;
});
},
items: {
search: function(query) {
return Restangular.all('products').getList(query);
}
},
};
});
How do I create params URL and function of this make restAPI calls or what are the workarounds in this case
You can get at the search parameters with the $location service. So if a user goes to somedomain.com/products/?page=2&orderby=asc then $location.search() will equal {page: 2, orderby: 'asc'}.
So when your controller loads you just need to set the filterCriteria and fetch the results.
controller
var myCtrl = function($location, $scope) {
$scope.selectPage = function(page) {
...
};
$scope.fetchResult = function() {
...
};
$scope.filterCriteria = $location.search();
$scope.fetchResults();
}
First you need to create a restangular object by mentioning the base url. In your case it will be
// It will creat a url /api
var base = Restangular.all('api');
Now you can create multiple scenarios like if you want to get all products then it will be:
// /api/products/
base.getList('products')
.then(function(products) {
$scope.products= products
})
Now if you want to apply pagination as well as include orderBy param
$scope.products = base.getList("products", [{page: 2},{orderby:asc}]);
I am just a beginner in Angularjs. I have been trying for consuming WebApi service by angularjs. I am following this
1: http://weblogs.asp.net/dwahlin/using-an-angularjs-factory-to-interact-with-a-restful-service documentation. It has been clearly documented about use of factories and services. I want to perform crud operations and I am following the same way but I am not even getting the methods called in the Api controller and how can I get the data to be listed in the view?
I have done this: My factory is defined in index.cshtml
In the Main view ie. Index.cshtml
#{
ViewBag.Title = "Index";
}
<style>
.container {
float: left;
width: 100%;
}
</style>
<script src="~/Scripts/angular.min.js"></script>
<h2>Practising Angular</h2>
List
Edit
<div ng-app="demoApp">
<div class="container">
<div ng-view=""></div>
</div>
</div>
<script>
var demoApp = angular.module('demoApp', []);
demoApp.config(function ($routeProvider) {
$routeProvider.when('/', { controller: 'SimpleController', templateUrl: 'Home/List' })
.when('/Edit', { controller: 'SimpleController', templateUrl: 'Home/Edit' })
.otherwise({ redirectTo: '/' });
});
demoApp.factory('dataFactory', ['$http', function ($http) {
var urlBase = '/api/Customer';
var dataFactory = {};
dataFactory.getCustomers = function () {
return $http.get(urlBase);
};
dataFactory.getCustomer = function (id) {
return $http.get(urlBase + '/' + id);
};
return dataFactory;
}]);
demoApp.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
$scope.customers;
getCustomers();
function getCustomers() {
dataFactory.getCustomers()
.success(function (custs) {
$scope.customers = custs;
})
.error(function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
}]);
</script>
I have this controller which runs by default as it is an MVC 4.0 project and "Home Controller" and "Index" is defined in the route.
namespace Routing_Angular.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult List()
{
return PartialView();
}
public ActionResult Edit()
{
return PartialView();
}
}
}
The List and Edit Action methods are returned as partialviews because they will act as views to render data in angular js.
So, this is what I have in both of the partial views..
List.cshtml
#{
ViewBag.Title = "List";
}
<h2>Listing the users in order </h2>
<div class="container">
Name: <input type="text" ng-model="filter.name" />
<ul>
<li ng-repeat="objCust in customers | filter:filter.name">{{objCust.name }}-{{objCust.city}}
</li>
</ul>
Customer Name:<br />
<input type="text" ng-model="newCustomer.name" /><br />
Customer city:<br />
<input type="text" ng-model="newCustomer.city" /><br />
<button ng-click="addCustomer()">Add customer</button>
</div>
Edit.cshtml
#{
ViewBag.Title = "Edit";
}
<h2>Edit the particular user. Things are under construction</h2>
<h2>Listing the users in order </h2>
<div class="container">
Name: <input type="text" ng-model="city" />
<ul>
<li ng-repeat="objCust in customers | filter:city">{{objCust.name }}-{{objCust.city}}
</li>
</ul>
</div>
This is the Api controller/Service that is being getting called from Factory in the index.cshtml. But none of the methods are getting called. How the data got from the factory objects will be shown in the View?
ApiController
namespace Routing_Angular.Controllers
{
public class CustomerController : ApiController
{
//
// GET: /Customer/
public HttpResponseMessage Get()
{
CustomerService ObjService = new CustomerService();
var Clients = ObjService.GetClients();
if (Clients.Count < 1) throw new HttpResponseException(HttpStatusCode.NotFound);
return Request.CreateResponse<IEnumerable<tblreferralService>>(HttpStatusCode.OK, Clients);
}
// GET api/customers/5
public HttpResponseMessage Get(int id)
{
CustomerService ObjService = new CustomerService();
var Client = ObjService.GetClient(id);
if (Client == null) throw new HttpResponseException(HttpStatusCode.NotFound);
return Request.CreateResponse<tblreferralService>(HttpStatusCode.OK, Client);
}
}
}
Below I am attaching the image for project structure. It is just a basic structure.