I am new to Angular JS. I have a MVC Area called "Setup". Under this area there is a Controller called ModuleMstController.
The above controller has an Action method GridData.
From my Angular controller i make a post with a url /Setup/ModuleMst/GridData
but firebug shows the request url as
http://localhost/ModuleMst/GridData
and my action method is not hit.
I then tried to configure routing as
var ap = angular.module('myApp', ['trNgGrid', 'ngRoute']);
//controller 1
ap.controller("MainCtrl", function ($scope, $http) {
$scope.model = {};
......
....
$scope.isAjaxInProgress = true;
$scope.errorMessage = undefined;
$http.post("/ModuleMst/GridData", $scope.requestedItemsGridOptions)
.then(function (data) {
$scope.model.itemList = data.items;
$scope.model.totalCount = data.TotalCount;
}
,function () {
$scope.errorMessage = "An Error has occured while loading data!";
});
})
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/ModuleMst', {
templateUrl: '/Setup/ModuleMst/GridData'
//controller: 'ModuleMst',
});
$routeProvider.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(false).hashPrefix('!');
}]);
I have not touched the routing configuration in the server side. It works with jquery ajax but not with angular $http.post().
How do i make this work ?
Thanks for the help.
Pass the MVC area in the http post:
$http.post("/Setup/ModuleMst/GridData", $scope.requestedItemsGridOptions)
Related
I've my backend developed in Silex with various routes that I can fully access using localhost:8080/project/api/index.php/user (example of a route).
if i'm coding an http get(I use only one controller called mainController ) in a js file using angular 1.5.8, how can I make that when I enter angularsite/user
(user is the route, "/user"), it returns me the data and then show it on my index.html ?
You need to set your app routes to your mainController controller.
angular.module('YourProject', [
'YourModule',
'ngRoute'
])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/user', {
templateUrl: 'view.html',
controllerAs: 'mainCtrl',
controller: 'mainController '
});
$routeProvider.otherwise({
redirectTo: '/user'
});
}])
Now when the page loads the RouteProvider will finds the default path to user (default route) route and that will load your view and controller. The templateUrl contains the route to the template.
If you only want to load a partial page you can do something like this..
'use strict';
var App = angular.module('YourProject', ['ngRoute', 'AppControllers']);
App.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/user', {
templateUrl: 'user.html'
}).
otherwise({
redirectTo: '/path'
});
}]);
Since your question mentions an API if you are trying to just load some data you can call user API with something like this from your controller (provided that the url given is an API which accepts GET request and responds with JSON data)..
var AppControllers = angular.module('AppControllers', []);
AppControllers.controller('MainController', ['$scope','$http', function ($scope, $http) {
//Declare a function to fetch user data from API
$scope.user= function () {
var req = {
method: 'GET',
url: baseURL + 'project/api/index.php/user'
}
return $http(req).success(function (data,status,header) {
$scope.user = data;
}).error(function () {
console.log(error);
});
}
//Call the get user function
$scope.user();
}]);
And finally in your partial file (user.html) add the controller to bind it with the controller declared above.
<!doctype html>
<html ng-app="YourProject">
<body>
<head>
<title>User Page</title>
</head>
<div class="user-content" ng-controller="MainController">
</body>
</html>
I want to build a Single Page Website, where my data is stored in a CMS. This CMS accepts Ajax Requests to serve me JSON. This JSON I want to output in my ng-app using the ui-router (I also tried the ngRoute before, with same results).
The Problem is: I need no template. Cause all my data I need comes from the JSON Request. But using no template or templateUrl doesn't affects the controller.
The question is how to output my received data in the HTML? I cant use ng-controller because it binds on only this specific controller. Console.log shows that my data is successfully received, but I found no way to get an output.
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise("/");
$stateProvider
.state('state1', {
url: '/state1',
template: '<h1>This Is A State</h1>',
controller: function($scope, $http) {
$scope.pageObj = '';
$scope.pageObj.url = '/angular/demo/';
$scope.pageObj.class = 'page-my';
$scope.pageObj.data = 'Empty';
$http
.get('/angular/demo/')
.then(function(result) {
console.log("Data Received");
console.log(result.data);
$scope.pageObj.data = result.data;
});
//console.log(result.data);
console.log("Hello state");
}
});
});
I found a small solution with using factory. The question is still, how do I access my data? Data now is stored by an own controller i guess. I post my updated code below:
var app = angular.module('myApp', ['ngSanitize', 'ngRoute', 'ui.router']).factory("dataService", function($http) {
var data = "";
var getData = function() {
return data;
}
var setData = function(newData) {
data = newData;
}
return {
getData: getData,
setData: setData
};
});
app.controller('FactoryCtrl', ['$scope', '$http', 'dataService', function($scope, $http, dataService) {
$scope.mydata = dataService.getData();
console.log($scope.mydata);
}]);
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise("/");
$stateProvider
.state('state1', {
url: '/state1',
template: '<h1>{{pageObj.data}}</h1>',
controller: function($scope, $http, dataService) {
$scope.pageObj = '';
$scope.pageObj.url = '/angular/demo/';
$scope.pageObj.class = 'page-my';
$scope.pageObj.data = 'Empty';
$http
.get('/angular/demo/')
.then(function(result) {
console.log("Data Received");
$scope.pageObj.data = result.data;
//$scope.model.data = dataService.getData();
dataService.setData("a string");
//console.log(dataService.getData());
});
console.log("Hello state");
}
});
});
I have an Angular app which makes some calls (POST and GET for now) to a backend service (powered by node.js with a REST interface). While developing the app itself I noticed it makes two requests to the backend each time a button is pressed or a page is loaded. Curiously everything works but each time I press some button the backend gets two requests. I am not using any fancy package only ngRoute, ngResource and routeStyles for css partials. Anybody has an idea of what could be the reason why the app behaves like that?
I actually found another question similar to this one but the OP there was using express aside of Angular and there is no answer...
EDIT added some code.
in app.js:
'use strict';
var cacheBustSuffix = Date.now();
angular.module('myApp', ['myApp.controllers', 'myApp.services', 'myApp.filters', 'ngRoute', 'ngResource', 'routeStyles'])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$locationProvider
.html5Mode({enabled: true,
requireBase: false})
.hashPrefix('!');
$routeProvider
.when('/', {redirectTo: '/myApp'})
.when('/myApp', {
templateUrl: '/partials/home.html?cache-bust=' + cacheBustSuffix,
controller: 'ctrlHome'
})
.when('/myApp/search', {
templateUrl: '/partials/search.html?cache-bust=' + cacheBustSuffix,
controller: 'ctrlSearch'
})
.when('/myApp/list/', {
templateUrl: '/partials/list.html?cache-bust=' + cacheBustSuffix,
controller: 'ctrlList'
})
// a bunch of other redirections
.otherwise({
templateUrl: '/partials/404.html?cache-bust=' + cacheBustSuffix,
controller: 'ctrl404'});
}]);
from services.js:
'use strict';
var app = angular.module('myApp.services', ['ngResource']).
factory('List', function ($resource) {
return $resource(WSROOT + '/search', {}, {get: {method: 'GET', isArray: false}});
});
from controllers.js, one controller that makes multiple requests
var controllers = angular.module('myApp.controllers', []);
var ctrlList = controllers.controller('ctrlList', function ($scope, $window, List) {
$window.document.title = 'myApp - List';
List.get({}, function (data) {
// $scope.res is an array of objects
$scope.res = data.response;
$scope.nitems = data.response.length;
});
});
ctrlList.$inject = ['$scope', 'List'];
And the network call when loading the index+home and navigating to some other page. As you can see, it first loads the index page, the scripts and styles listed there (not shown), then the home where I have a controller similar to the one above and suddenly two wild request to my web server:
Can we see your HTML files? I had this problem a while back. My solution was that by declaring a controller in the routing, and in the pages, a double post was created as each controller was loaded twice.
//Home
.state('tab.home', {
url: '/home',
views: {
'tab-home': {
templateUrl: 'templates/tab-home.html',
controller: 'HomeCtrl' // <-- This goes away
}
}
})
Fairly new to AngularJS and WebAPI here, and figure the best way to learn is by doing. Apologies in advance if this question seems simple - I've spent a day flipping through StackOverflow and tried them all.
I currently have a separate Master & Detail view, both with their own controller. I am trying to pass the selected ID through to the Details controller so I can query my database using the ID, though am getting "undefined" on my $routeParams. I'm unsure if I am missing something simple, or whether I'm even approaching this correctly.
The controller doesn't seem to like it when I inject '$routeParams' either.
My app.js module:
var app = angular.module("ProjectDashboardModule", ["ngRoute"]);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when("/", { templateUrl: "/Home/Index" })
.when("/Project", { templateUrl: '/Project/Index', controller: 'ProjectCrudController' })
.when("/Project/project/:id", {templateUrl:'/Project/project', controller: 'ProjectTaskController' });
$routeProvider.otherwise({redirectTo: '/home' });
$locationProvider.html5Mode(true);
}]);
my Factory.js:
app.factory('projectFactory', ['$http', function ($http) {
var urlBase = '/api/Projects/';
var projectFactory = {};
projectFactory.getProjects = function () {
return $http.get(urlBase);
};
projectFactory.getSingleProject = function (id) {
return $http.get(urlBase + '/' + id);
};
return projectFactory;
}]);
my ProjectTaskController.js:
app.controller('ProjectTaskController', ['$scope', "$routeParams", 'projectFactory', function ($scope, $routeParams, projectFactory) {
alert($routeParams.id)
$scope.project;
$scope.message;
getProjectById($routeParams.id);
function getProjectById(id) {
projectFactory.getSingleProject(id)
.success(function (data) {
$scope.project = data;
})
.error(function (error) {
$scope.message = 'error retrieving project ' + error.message;
});
}
}]);
I found that my problem was that all my angular script references were scattered. I moved all my custom script references (controller, factory, module) to index.cshtml and fixed the issue.
I am using controller in my Angularjs which gets question one by one from server and i want on specific condition this controller should call a routeprovider that should change my current view with templateUrl and put into a directive
my question is can i call route provider in controller rather than module
here is my CreateController
var CreateController = ['$scope', '$http', function ($scope, $http) {
$scope.model = {
};
................>
.................>
$scope.NextQuestion = function () {
$http.post('/Testing/NextQuestion', {
........................>
}).success(function (newdata) {
$scope.model = newdata;
var inccomplevel = $scope.model.servercomplevel;
if (qId == 10) {
here i need the code for routeProvider and directive please provide me help
}
......................>
}];
i did the route provider in app.js file there it works
here is the code for app.js when i do like this it works and when i shift the code of route provider
to the create controller in condition if qId == 10 there it does not work
var app = angular.module('app', ['ngRoute']);
app.controller('CreateController', CreateController);
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: 'Partials/TestCompleted.html',
controller: 'AppCtrl'
})
.otherwise({ redirectTo: '/' });
});
app.controller("AppCtrl",function ($scope) {
$scope.newmodel = {
}
});
Instead of trying to change the value of the templateUrl on the route, you should define another route. Then you can simply switch routes.
To change the route/view, you need update the path. You can do this using the $location service.
See AngularJS : How do I switch views from a controller function?