I am trying to change the URL of the page if an $html callback is a success.
Module:
var app = angular.module('mymodule', ['ngRoute','ui.bootstrap']);
app.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/Home/Index', {
templateUrl: '/Home/Index',
controller: 'HomeController'
});
});
Controller:
$http({
method: 'POST',
url: '/User/InsertInitialUserInfo',
data: insertUserParams
}).success(function (data, status) {
$location.url("/Home/Index");
}).error(function (data, status) {
console.log(status);
});
MVC Controller
public ActionResult Index()
{
return View();
}
After my controller code runs the URL changes from : localhost:xxxx/Home/Register to localhost:xxxx/Home/Index
But the view doesn't change. What am I missing?
You are only missing one important component, the ng-view declaration in your view
<div ng-view></div>
This is placeholder for the templates you specify in the app.config.
Related
My layout.cshtml contains:
<li>User</li>
<div ng-view></div>
This is my controller:
and its action methods:
public class UserController : Controller
{
// GET: Admin/Default
BMS2Entities _db = new BMS2Entities();
public ActionResult Index()
{
var emp = _db.AspNetUsers.ToList();
return Json(emp, JsonRequestBehavior.AllowGet);
}
And index.cshtml and index.js file inside:
index.js contains server call to usercontroller inside admin area:
app.controller('userController', function ($scope, $http) {
$http({ method: 'Get', url: 'Areas/Admin/User/Index' })
.then(function (response) {
$scope.depts = response.data;
});
});
and finally myapp.js file for routing:
var app = angular.module('myAppS', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/User', {
templateUrl: 'Areas/Admin/Views/User/Index.cshtml',
controller: 'userController'
});
$routeProvider.otherwise({
redirectTo: '/'
});
});
but the codes are not working and it does not display cshtml and shows
https://localhost:44382/Common/Home#/User in the browser.
$routeProvider.when('/User', {
templateUrl: 'Areas/Admin/Views/User/Index.cshtml',
controller: 'userController'
});
You need to prefix root path in templateUrl and same thing in while calling controller's action.
Did you write ng-app directive in layout.cshtml?
And I think the syntax for tag should be like
User
Hope this Helps!
Very simply, after an API call, depending on the return value, how is the appropriate view loaded? Consider having
search.html
views/found.html
views/notfound.html
Search's controller makes an AJAX call to a service and gets a good or bad result. Now I want the appropriate view to load, without user having to click. I just can't figure out how to do this and have looked at scores of routing/view examples. I'm using HTML5 mode.
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'search.html',
controller: 'searchCtrl'
})
.when('found', {
templateUrl: 'views/found.html',
controller: 'foundCtrl'
})
.when('notFound', {
templateUrl: 'views/notFound.html',
controller: 'notFoundCtrl'
})
.otherwise({
templateUrl: 'search.html',
controller: 'searchCtrl'
});
$locationProvider.html5Mode({
enabled: true,
requiredBase: true
});
And in the controller ..
$scope.post = function (requestType, requestData) {
var uri = 'Search/' + requestType;
$http.post(uri, requestData)
.success(function (response) {
$scope.searchResult.ID = response.ID;
$scope.searchResult.Value = response.Value;
// how is the view/route loaded without a user click?
'found';
return true;
}).error(function (error) {
// how is the view/route loaded without a user click?
'notFound';
return false;
});
I'm just lost after getting back the response on how to invoke a view within the template.
Since you are using ngRoute use $location.path() instead of $state.go(). The $location.path() method accepts a url specified in route configuration. E.g.:
$location.path('/found');
Say your controller is AppController, then the complete code will look something like:
angular.module('app', ['ngRoute'])
.controller('AppController', function ($location, $http) {
$scope.post = function (requestType, requestData) {
var uri = 'Search/' + requestType;
$http.post(uri, requestData)
.success(function (response) {
$scope.searchResult.ID = response.ID;
$scope.searchResult.Value = response.Value;
// how is the view/route loaded without a user click?
$location.path('/found');
}).error(function (error) {
// how is the view/route loaded without a user click?
$location.path('/notFound');
});
});
Refer https://docs.angularjs.org/api/ng/service/$location for api documentation of $location.path
I'm using angular 1.5.0-beta2
i want to be able to read the parameter /cocktail/:cocktail_name
here i define the app and controller:
var app = angular.module('myalcoholist',['ngMaterial','ngRoute']);
app.controller('CocktailController',['$scope','$http', function ($scope,$http) {
$scope.cocktailStepsRows=null;
$http({
method: 'GET',
url: 'http://api.myalcoholist.com:8888/cocktail/steps/' + $scope.cocktail_name
}).then(function successCallback(response) {
$scope.cocktailStepsRows=response.data;
}, function errorCallback(response) {
alert('error');
});
}]);
as you can see i'm trying to append to the api url $scope.cocktail_name
this is how i configure ng-view:
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/',{
templateUrl: 'views/index.html',
controller: 'IndexController'
}).
when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginController'
}).
when('/cocktail/:cocktail_name', {
templateUrl: 'views/cocktail.html',
controller: 'CocktailController'
}).
otherwise({
redirectTo: '/'
});
}]);
as you can see i configured the route properly to receive the cocktail_name parameter.
now the problem i'm having is that in the controller, $scope.cocktail_name is undefined.
in the view when i print cocktail name
{{cocktail_name}}
I receive the parameter properly. why not in the controller?
what am I missing?
You did not copy the parameter value to the scope. Fix it using:
$scope.cocktail_name = $routeParams.cocktail_name
I'm trying to load routes from server. when user navigate to a route via link it works perfectly, but when user hit F5 or open a route from bookmarks page will be empty. I tried $state.reload() after for loop but it causes "Cannot transition to abstract state '[object Object]'" error
var app = angular
.module("app ", ["ui.router"])
.config(function ($stateProvider, $urlRouterProvider) {
app.stateProvider = $stateProvider;
app.urlRouterProvider = $urlRouterProvider;
})
.run(function ($http, $state, $stateParams) {
$http({
method: 'POST',
url: '/Config/GetRoutes'
}).success(function (data, status) {
for (i in data.routes) {
app.stateProvider.state(data.routes[i].name, {
url: "/" + data.routes[i].name,
templateUrl: data.routes[i].url,
controller: 'sectionController'
});
}
});
})
;
Finally I found my answer!
var app = angular
.module("app ", ["ui.router"])
.config(function ($stateProvider, $urlRouterProvider) {
app.stateProvider = $stateProvider;
app.urlRouterProvider = $urlRouterProvider;
//defer intecepting
$urlRouterProvider.deferIntercept();
})
.run(function ($http, $state, $stateParams) {
$http({
method: 'POST',
url: '/Config/GetRoutes'
}).success(function (data, status) {
for (i in data.routes) {
app.stateProvider.state(data.routes[i].name, {
url: "/" + data.routes[i].name,
templateUrl: data.routes[i].url,
controller: 'sectionController'
});
}
// intecepting again
$urlRouter.sync();
$urlRouter.listen();
});
})
;
Hi I believe better solution is to write a provider to add routes dynamically, then use that in run function.
http://plnkr.co/edit/C2gXMo?p=preview
app.provider("DinamicRouteProvider", DinamicRouteProvider);
function DinamicRouteProvider($stateProvider) {
return {
$get: function( $state ) {
return {
addRoute: function (route){
$stateProvider
.state(route.name, {
url: '/' + route.name,
template: '<div><h2>This is '+route.name+'</h2></div>',
controller: 'DynCtrl'
});
console.log('State added', route)
}
};
}
};
}
I'm new to Angular and I'm trying to create a Single Page application with 2 views.
When I load the app is always shows me the first one of the 2 views regardless of what route I type in the browser.
This is the javascript code:
var appControllers = angular.module('appControllers', []);
appControllers.controller('HomeController', function($scope, $http) {
var promise = $http({
method: 'GET',
url: 'restaurant.json'
});
promise.then(function(obj) {
$scope.data = obj.data;
});
});
appControllers.controller('InformationController', function($scope, $http) {
var promise = $http({
method: 'GET',
url: 'restaurant.json'
});
promise.then(function(obj) {
$scope.data = obj.data;
});
});
var app = angular.module('myApp', ['ngRoute', 'appControllers']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/productlist.html',
controller: 'HomeController'
}).
when('/info', {
templateUrl: 'partials/information.html',
controller: 'InformationController'
})
}]);
app.controller('HomeController', function($scope, $http) {
var promise = $http({
method: 'GET',
url: 'restaurant.json'
});
promise.then(function(obj) {
$scope.data = obj.data;
});
});
app.controller('InformationController', function($scope, $http) {
var promise = $http({
method: 'GET',
url: 'restaurant.json'
});
promise.then(function(obj) {
$scope.data = obj.data;
});
});
I tried to change the order in which I define the 2 routes for the 2 view templates.
If I define the info template first the that template will be shown always and the other one will not be shown.
Can someone help me fix this problem?
Here is a fully functioning ngRoute:
sampleApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/a', {
templateUrl: 'templates/a.html',
controller: 'a'
}).
when('/av2', {
templateUrl: 'templates/av2.html',
controller: 'av2',
}).
when('/a3', {
templateUrl: 'templates/a3.html',
controller: 'a3'
}).
otherwise({
redirectTo: '/a'
});
}]);
Try cross comparing that with your code and see if you find any differences. I think it may have to do with how you initiate your app very late into the script:
var app = angular.module('myApp', ['ngRoute', 'appControllers']);
Typically, bootstrapping your app is one of the most important things to do and should be at the top as a result.