Angular load selectlist with json from mvc controller - javascript

Here is my view:
<div>
<select ng-model="firstSupplier" ng-options="firstSupplier as firstSupplier.SupplierName for firstSupplier in jsonSuppliers"></select>
</div>
and here is my angular controller:
(function() {
var app = angular.module("CustCMS");
var indexController = function($scope, $http) {
$http.get("/Home/GetAllSuppliers")
.then(function (response) {
$scope.jsonSuppliers = response.data;
$scope.firstSupplier = $scope.jsonSuppliers[0];
});
};
app.controller("IndexController", ["$scope", "$http", indexController]);
}());
and here is my mvc controller:
public JsonResult GetAllSuppliers()
{
var suppliers = GetAll();
return Json(new { data = suppliers}, JsonRequestBehavior.AllowGet);
}
here is the json that returns to the angular controller jsonSuppliers:
{"data":[{"SupplierId":1,"SupplierName":"Normstahl","PrefixCountryCode":"NS01COUNTRY","UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":2,"SupplierName":"TestSupplier 2","PrefixCountryCode":null,"UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":3,"SupplierName":"Ditec","PrefixCountryCode":"DIIT01COUNTRY","UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":4,"SupplierName":"Ospf","PrefixCountryCode":"CRCOUNTRY","UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":5,"SupplierName":"Alsta","PrefixCountryCode":null,"UseOrderSystem":false,"IsDirect":false,"Customers":[]}]}
Is where something that im missing here?
I don't get any errors in the console....
Is there an easier way to do it that would be much appreciated!

Related

How to pass form data to another page?

im using angularJS v 1.5.6 and want to know how to pass my form data correctly with $location.path.
Here is my code Page A:
<form>
...
<button type="submit" ng-click="submit(formData)">submit</button>
</form>
JS:
app.config(['$routeProvider', function ($routeProvider) {$routeProvider
// Home
.when("/", {
templateUrl: "A.html",
controller: "ACtrl"
})
.when("/B/", {
templateUrl: "B.html",
controller: "BCtrl"
})
//fallback url if nothing matches
.otherwise({
redirectTo: '/'
});
}]);
app.controller('ACtrl', function ( $scope, $location, $http) {
$scope.formData = {};
$scope.submit = function() {
$location.path("/B/" + $scope.formData );
};
});
//controller for B page
app.controller('BCtrl', ['$scope', '$routeParams',
function($scope,$routeParams) {
$scope.formData = $routeParams.formData;
}]);
it is a pretty simple example, but i cant figure out how to solve it :(
By clicking the submit nothing happens. If i remove the $scope from $scope.formData i get a error like: Error: formData is not defined.
The terms in formdata are available, i tested it with console.log($scope.formData) and everything is ok.
here is the link plunker: https://plnkr.co/edit/K5zwcmRRyom5HR4a5Q9o
EDIT
the only issue is now, how to handle the select object correctly in the foreach loop. Need help please
You can do it by creating a service and using setter/getter in order to transfer a variable.
For example like this: https://plnkr.co/edit/IuTXsVLU7dq3TylfnSYP?p=preview
app.service('TransferService', [function(){
var savedData,
service = {
getData: getData,
setData: setData
}
function getData(){
return savedData
}
function setData(data){
savedData = data
}
return service
}])
Don't use location.path...
You could either use a service or use localstorage (or some other browser storage mechanism [sessionStorage, indexdb].
Service Method Below
app.service("SomeService", function () {
var value = null;
this.set = function (val) {
value = val;
return this;
}
this.get = function () {
return value;
}
})
app.controller("ACtrl", function ($scope, SomeService) {
$scope.formData = {};
$scope.submit = function() {
//Assuming you've populated it with some data...
SomeService.set($scope.formData);
$location.path("/B/");
};
})
app.controller("BCtrl", function ($scope, SomeService) {
$scope.formData;
(function () {
//Check that the data is present in the SomeService service.
var dataFromACtrl = SomeService.get();
if (dataFromACtrl) {
$scope.formData = dataFromACtrl;
}
})();
})
Using localStrorage below, could be sessionStorage.
app.controller("ACtrl", function ($scope, SomeService) {
$scope.formData = {};
$scope.submit = function() {
//Assuming you've populated it with some data...
window.localStorage.setItem("form_data", JSON.stringify($scope.form_data));
$location.path("/B/");
};
})
app.controller("BCtrl", function ($scope, SomeService) {
$scope.formData;
(function () {
var dataFromACtrl = window.localStorage.getItem("form_data");
if (dataFromACtrl) {
$scope.formData = JSON.parse(dataFromACtrl);
}
})();
})
Note
Using the localStorage example you would need to do some clean-up, after doing whatever you want to do with that data in Bctrl you'd want to clear the entry in localstorage using either of the below lines of code:
window.localStorage.removeItem("form_data");
delete window.localStorage["form_data"];

Accessing a dictionary from angular controller

I'm trying to do the following.
Angular controller calls and MVC controller GET method. This method then calls into a REST API on the web which returns a list of configuration items. I then turn this into a dictionary so I can look up configuration values based on the key, and then I want to pass this back to the Angular controller and store it there in a variable that I can access from many different scenarios, eg displaying them in grids, updating values, changing and updating them back to the REST API etc. I have tried to set up the pipes but I can't seem to get the data in a readable/usable format in the Angular controller.
My controller
app.controller("SEFlexHomeController", ["$scope", "$http", "$modal", "$log", "$element", "$rootScope", "AlertsService", "AuthService", "SEApplicationService", function ($scope, $http, $modal, $log, $element, $rootScope, AlertsService, AuthService, SEApplicationService) {
$rootScope.closeAlert = AlertsService.closeAlert;
$scope.isDataLoading = false;
$scope.AuthService = AuthService;
$scope.configvalues = angular.fromJson(SEApplicationService.getCloudConfigParams());
}
]);
My Angular Service
app.factory("SEApplicationService", ["$log", "$http", "$timeout", function($log, $http, $timeout) {
var appService = {};
appService.getCloudConfigParams = function () {
return $http.get("/SEFlex/SEFlexAdmin/GetCloudConfigValues");
}
return appService;
}]);
My MVC controller
public ActionResult GetCloudConfigValues()
{
try
{
var helper = new ApplicationServiceHelper();
var dictionary = helper.GetCloudConfigValues()
.ToList()
.ToDictionary(item => item.ConfigKey, item => item.ConfigValue);
var returnData = JsonConvert.SerializeObject(dictionary);
return Json(new
{
success = true,
data = returnData
}, JsonRequestBehavior.AllowGet);
}
catch (Exception exception)
{
return Json(new
{
success = false,
errors = new[] { exception.Message }
});
}
}
I can confirm at the time of creating the Dictionary in the MVC controller, the dictionary looks as expected for a .NET dictionary. What do I need to do to convert this either before transmission back or back in Angular, so that I can access it in angular as
$scope.configvalues["keyName"]
The $http.get() call returns a promise. You should change the
$scope.configvalues = angular.fromJson(SEApplicationService.getCloudConfigParams());
to
SEApplicationService.getCloudConfigParams().then(function(config) {
$scope.configvalues = config;
});

Angular-JS routing get data from MVC controller

I have implemented code to retrieve data from MVC Controller using Angular-JS using ngRoute. What I have implemented is, I have two action methods in MVC controller and at client side I have two menu buttons and by clicking on each button, it retrieves data from respective action method. I have used Angular-Route, Angular Factory Method and ng-view
Till now it is fine. But what I can see is AngularJS doesn't go to Action Method every time when i click on the button. Once data have been retrieved, it only shows the respective view. And in this situation I cannot retrieve fresh data from database. So If I have to call action method every time how can I achieve this ?
This is what I have implemented:
AccountController:
public ActionResult GetAccounts()
{
var repo = new AccountRepository();
var accounts = repo.GetAccounts();
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var jsonResult = new ContentResult
{
Content = JsonConvert.SerializeObject(accounts, settings),
ContentType = "application/json"
};
return jsonResult;
}
public ActionResult GetNumbers()
{
var repo = new AccountRepository();
var numbers = repo.GetNumbers();
var setting = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var jsonResult = new ContentResult()
{
Content = JsonConvert.SerializeObject(numbers, setting),
ContentType = "application/json"
};
return jsonResult;
}
Account.JS:
'use strict';
var account = angular.module('accountModule', ['ngRoute']);
account.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/Employees', { templateUrl: '../Templates/Employees.html', controller: 'accountController' })
.when('/Numbers', { templateUrl: '../Templates/Numbers.html', controller: 'numberController' })
.otherwise({
redirectTo: '/phones'
});;
}]);
account.controller('accountController', [
'$scope',
'accountService',
function ($scope, accountService) {
accountService.getEmployees().then(function(talks) {
$scope.employees = talks;
}, function() {
alert('Some error');
});
}
]);
account.controller('numberController', [
'$scope',
'accountService',
function ($scope, accountService) {
accountService.getNumbers().then(function (retrievedNumbers) {
$scope.telephoneNumbers = retrievedNumbers;
}, function () {
alert('error while retrieving numbers');
});
}
]);
AccountService.JS:
account.factory('accountService', ['$http', '$q', function ($http, $q) {
var factory = {};
factory.getEmployees = function () {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'GetAccounts'
}).success(deferred.resolve).error(deferred.reject);
return deferred.promise;
};
factory.getNumbers = function () {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'GetNumbers'
}).success(deferred.resolve).error(deferred.reject);
return deferred.promise;
};
return factory;
}]);
and my view is something like this:
#{
ViewBag.Title = "Index";
Layout = "~/Views/shared/_Layout.cshtml";
}
<script type="text/javascript" src="../../Scripts/Modules/Account/Account.js"></script>
<script type="text/javascript" src="../../Scripts/Modules/Account/AccountService.js"></script>
<div ng-app="accountModule">
<div>
<div class="container">
<div class="navbar navbar-default">
<div class="navbar-header">
<ul class="nav navbar-nav">
<li class="navbar-brand">Employees</li>
<li class="navbar-brand">Numbers</li>
</ul>
</div>
</div>
<div ng-view>
</div>
</div>
</div>
</div>

how to use a common service for different json data in angularjs?

I created a service that fetches data from local json and use it in a controller to display it in browser. All are working fine. here is my code:
JS Code:
var myApp = angular.module("myApp", ['ngRoute']);
myApp.service("dataService", function($http, $q){
var deferred = $q.defer();
$http.get('json/link.json').then(function(data){
deferred.resolve(data);
});
this.getData = function(){
return deferred.promise;
}
})
.controller("linkCtrl", function($scope, dataService) {
var promise = dataService.getData();
promise.then(function(data) {
$scope.links = data.data;
});
});
Now, i have another json link (for eg.: json/link2.json ) and i want to perform the same function. Is there any way to use the "dataService" service ( like changing the link ).
I don't want to re-create a new service which does the same function. Any idea to re-use the Service for different json data ?
Thanks in Advance
Just create a method you can pass url to:
myApp.service("dataService", function($http){
this.getData = function(url){
return $http.get(url); // this returns a promise
};
})
Use it like this:
.controller("linkCtrl", function($scope, dataService) {
var promise1 = dataService.getData('json/link.json');
promise1.then(function(data) {
$scope.links = data.data;
});
var promise2 = dataService.getData('json/link2.json');
promise2.then(function(data) {
$scope.links2 = data.data;
});
});
Try something like this
myApp.service("dataService", function($http){
this.getData = function(link,callback){
$http.get(link).then(function(data){
if(callback)
callback(data);
});
});
myApp.controller("linkCtrl", function($scope, dataService) {
dataService.getData('json/link.json', function(data){
$scope.links = data.data;
});
});

AngularJs controller get request not hitting Spring MVC Rest Service

So I have my angular javascript as
var app = angular.module('app', []);
app.controller('controller', function($scope, $http) {
$http.get('http://localhost:8080/core/students.json')
.success(function(data) {
$scope.user = data;
});
});
and my rest controller with
#RestController
public class StudentRestController {
#RequestMapping(value = "/students", produces = { "application/json" }, method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public Student getStudent() {
// return studentService.getStudentByUserName(userName);
Student s = new Student();
s.setUserName("userName");
s.setEmailAddress("email");
return s;
}
}
but for some reason, the javascript ajax request isn't hitting the method getStudent(). Why is this? I get a console error
"GET http://localhost:8080/core/students.json 404 (Not Found)"
ordinary button url calls work as expected
change angularjs app as
var app = angular.module('app', []);
app.controller('controller', [ "$scope", "$http", function($scope, $http) {
$http.get("http://localhost:8080/students").success(function(data) {
$scope.user = data;
});
} ]);
that holds if ur web.xml
<servlet-mapping>
<servlet-name> dispatcherServlet </servlet-name>
<url-pattern> * </url-pattern>
</servlet-mapping>
You are defining "/students" on the #RequestMapping, then your URL should be ".../core/students".

Categories

Resources