Angularjs app not triggered - angularjs

For some reason my Angular site isn't working. I've included all the files. but for some reason angular isn't triggered to do something.
This is how my index.html looks like:
<!DOCTYPE html>
<html ng-app="ngTest">
<head>
<title></title>
</head>
<body>
<h2>Test</h2>
<ng-view></ng-view>
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-resource.js"></script>
<script src="Scripts/angular-route.js"></script>
<script src="Scripts/angular-animate.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/home/HomeCtrl.js"></script>
</body>
</html>
All included scripts return 200 in the developer console, so I'm sure they are loaded fine.
Then my app.js looks like this:
window.app = angular.module('ngTest', ['ngRoute', 'ngResource', 'ngAnimate']);
app.config(['$routeProvider', '$locationProvider', '$httpProvider', '$provide', function ($routeProvider, $locationProvider, $httpProvider, $provide) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.useXDomain = true;
$locationProvider.html5Mode(true);
$routeProvider
.when('/Home', { templateUrl: '/app/views/home/Home.html', controller: 'HomeCtrl' })
.otherwise({ redirectTo: '/Login' });
}]);
The HomeCtrl.js simply looks lke this:
app.controller('HomeCtrl', ['$scope', function ($scope) {
init();
function init() {
alert('aaa');
}
}]);
And the Home.html only contains a piece of text.
Then when I navigate to: localhost/#Home then I expect it to load my Home.html in the ng-view tag. But that's not happening. It only loads my index.html but no angular code seems to be triggered.
Am I still missing something?

Try:
angular.module('ngTest', ['ngRoute', 'ngResource', 'ngAnimate']).
config(['$routeProvider', '$locationProvider', '$httpProvider', '$provide', function ($routeProvider, $locationProvider, $httpProvider, $provide) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.useXDomain = true;
$locationProvider.html5Mode(true);
$routeProvider.when('/Home', {
templateUrl: '/app/views/home/Home.html',
controller: 'HomeCtrl'
})
.otherwise({
redirectTo: '/Login'
});
}]);
You could do that for controlers :
angular.module('ngTest.controllers', []);//Declare controllers
angular.module('ngTest.controllers').
controller('HomeCtrl',['$scope', function ($scope) {
init();
function init() {
alert('aaa');
}
}]);
By the way, with html5Mode(true) your path will be localhost/Home.

Related

angularjs http-server reload state not working

I have a small AngularJS test app and am running http-server. I am using ui-router. When I load localhost:8080 my angular component works fine. When I click on <a ui-sref="new">New</> I go to localhost:8080/new and the new component loads fine. However, when I reload the page, the product-details component doesn't load
app.js
'use strict';
angular
.module('productApp', [
'ui.router',
'ProductComponents',
])
.config([
'$httpProvider',
'$locationProvider',
'$stateProvider',
'$urlRouterProvider',
'$compileProvider',
function($httpProvider, $locationProvider, $stateProvider, $urlRouterProvider, $compileProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
$compileProvider.debugInfoEnabled('<%= Rails.env.development? %>');
var token = document.querySelector('meta[name="csrf-token"]');
if(angular.isElement(token)){
$httpProvider.defaults.headers.common['X-CSRF-Token'] = token.content;
}
$httpProvider.useApplyAsync(true);
$httpProvider.defaults.paramSerializer = '$httpParamSerializerJQLike';
// For any unmatched url, redirect to /state1
$urlRouterProvider
.otherwise("/");
$stateProvider
.state('root', {
url: "/",
template: '<product-index meta="meta"></product-index>'
})
.state('new', {
url: "/new",
template: '<product-new></product-new>'
})
}])
index.html
<!DOCTYPE html>
<html>
<head>>
<script src="angular.js"></script>
<script src="angular-resource.js"></script>
<script src="//unpkg.com/#uirouter/angularjs/release/angular-ui-router.min.js"></script>
<script src="select.js"></script>
<script src="product_components.js"></script>
<script src="product_index.js"></script>
<script src="product_new.js"></script>
<script src="product_details.js"></script>
<script src="app.js"></script>
<base href="/">
</head>
<body>
<div ng-app="productApp">
<ui-view></ui-view>
</div>
</body>
</html>
product-new.js
'use strict';
angular
.module('ProductComponents')
.component('productNew', {
bindings:{
},
templateUrl: "new.html",
controllerAs: 'prodNew',
controller: function(){
var prodNew = this;
prodNew.product = { name: 'Test Product' };
}
}
)
new.html
<h2>Products</h2>
<product-details product="prodNew.product"></product-details>
product-details.js
angular
.module('ProductComponents')
.component('productDetails', {
bindings:{
product: '=product',
},
templateUrl: "details.html",
controllerAs: 'prodDetails',
controller: [
'$filter',
// '$http',
function(
$filter,
// $http,
){
var prodDetails = this;
...

How to start my asp.net mvc application with the Angular hashbang url?

When I start my asp.net mvc application (www.mysite.com), the home controller index action is loaded.
This action serves a view, and in that view my AngularJS app is loaded.
However, my AngularJS app wants to be started at www.mysite.com/#!/
Is there a way to force this, that when you go to the root that it gets redirected to /#!/ ?
What I have now is this:
<system.webServer>
<defaultDocument enabled="true">
<!-- this line enables default documents for a directory -->
<files>
<clear/>
<!-- removes the existing default document list -->
<add value="/#!/"/>
</files>
</defaultDocument>
but as you can guess this doesn't work.
I tested it at my local IIS and at Azure.
EDIT
To clarify: If I don't put the /#!/ at the end or the url, Angular does not kick in. Maybe that is the problem, that I do not have my config right?
my home state is this:
.state(appConfig.routes.home, {
url: "/",
views: {
'content': { templateUrl: "/Js/views/home/home.html", controller: 'ikvhomecontroller as vmhome' },
'homeheader#index.home': { templateUrl: "/Js/views/shared/sharedheader.html", controller: 'sharedheadercontroller as vmshhe' }
}
})
This is my config:
(function () {
'use strict';
angular.module(Main.config.name, [
// Angular modules
'ngResource',
'ngSanitize',
// Custom modules
// 3rd Party Modules
'ui.router',
'ngAnimate'
])
.constant('appConfig', Main)
.config(['$locationProvider', '$stateProvider', 'appConfig', '$httpProvider', '$urlRouterProvider', function ($locationProvider, $stateProvider, appConfig, $httpProvider, $urlRouterProvider) {
console.log('yep, I am at .config');
if (appConfig.useHtml5Mode)
$locationProvider.html5Mode(true);
else {
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix('!');
};
$urlRouterProvider.otherwise("/");
$urlRouterProvider.when('/', 'index.home');
$stateProvider
.state('index', {
url: "",
views: {
"#": { templateUrl: "/Js/views/main.html" },
"header#index": { templateUrl: "/Js/views/header.html", controller: "menucontroller as vm" },
'content#index': { templateUrl: "/Js/views/content.html" },
"footer#index": { templateUrl: "/Js/views/footer.html" }
}
})
.state(appConfig.routes.home, {
url: "/",
views: {
'content': { templateUrl: "/Js/views/home/home.html", controller: 'homecontroller as vmhome' },
'homeheader#index.home': { templateUrl: "/Js/views/shared/sharedheader.html", controller: 'sharedheadercontroller as vmshhe' }
}
});
}])
.run([
'$http',
'$state',
'$rootScope',
'$templateCache',
function ($http, $state, $rootScope, $templateCache) {
$rootScope.$on("$stateChangeError", console.log.bind(console));
$rootScope.$on('$locationChangeSuccess', function (evt) {
console.log(evt);
});
$templateCache.removeAll();
}]);
})();
This is the html in the browser:
<div id="main" ui-view>
<div class="imgwrapper"><img src="/Images/iloading.gif" /></div>
</div>
<script src="/Scripts/jquery-2.2.0.js"></script>
<script src="/Scripts/modernizr-2.8.3.js"></script>
<script src="/Scripts/moment-with-locales.js"></script>
<script src="/Scripts/uihelpers/currencykeydown.js"></script>
<script src="/Scripts/uihelpers/datekeydown.js"></script>
<script src="/Scripts/uihelpers/labeltitleclick.js"></script>
<script src="/Scripts/uihelpers/textareagrow.js"></script>
<script src="/Scripts/respond.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-route.js"></script>
<script src="/Scripts/angular-resource.js"></script>
<script src="/Scripts/angular-sanitize.js"></script>
<script src="/Scripts/angular-animate.js"></script>
<script src="/Scripts/angular-locale_nl-nl.js"></script>
<script src="/Scripts/angular-ui-router.js"></script>
<script src="/Scripts/config.js"></script>
<script src="/Scripts/App.js"></script>
<script src="/Scripts/helpers/calcutils.js"></script>
<script src="/Scripts/helpers/dateutils.js"></script>
<script src="/Scripts/helpers/SelectHelper.js"></script>
and the rest of my custom code goes here
you should modify your 'route.config.js' in angularjs like as -
angular.module('yourModuleName').config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider.
state('login', {
url: 'login',
templateUrl: '/path/to your login page',
});
$urlRouterProvider.otherwise("/");
$urlRouterProvider.when('/', 'login');
}
]);
This will automatically route your page to localhost/#!/login when you start your application.

Angular routing with parameter issue

I have MVC application, I want make routing for the following URL
http://localhost:2668/Home/User/1
I try
.config(function ($routeProvider, $locationProvider) {
//here we will write code for implement routing
$routeProvider
.when('#/Home/User/:userid', {
templateUrl: '/AngularTemplates/User.html',
controller: 'UserController'
})
.otherwise({ // This is when any route not matched
controller: 'ErrorController'
}) })
And then the UserController as below:
.controller('UserController', ['$scope','$routeParams', function ($scope,$routeParams) {
// $routeParams used for get query string value
//var loc = window.location.href;
//var id = loc.slice(loc.lastIndexOf('/'), loc.length).split('/')[1];
$scope.Message = "This is ORDER Page with query string id value =" + $routeParams.userid;
}])
But I always get "undefined" for the para $routeParams.userid
What is wrong in my code? Please help thanks!
Here is a working example:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
user 11
user 12
<div ng-view></div>
<script>
var app = angular.module('app', ['ngRoute']);
app.config([
'$locationProvider', '$routeProvider',
function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
}).hashPrefix('!');
$routeProvider
.when('/Home/User/:userid', {
template: '<pre>{{ message }}</pre>',
controller: 'UserController'
});
}]);
app.controller('UserController', ['$scope','$routeParams', function ($scope, $routeParams) {
$scope.message = "userid = " + $routeParams.userid;
}]);
</script>
</body>
</html>
JSBin http://output.jsbin.com/geluli
You may read more about default router here (nice examples + tests) https://docs.angularjs.org/api/ngRoute/service/$route

AngularJS: Controller is not getting called

I have following html file
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en-US">
<head>
<script src="{% static 'bower_components/angular/angular.js' %}"></script>
<script src="{% static 'bower_components/angular-route/angular-route.js' %}"></script>
<script src="{% static 'js/hearthstone_guides/controllers.js' %}"></script>
<script src="{% static 'js/hearthstone_guides/app.js' %}"></script>
</head>
<body ng-app="guideApp">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello [[name]]</h1>
<div ng-view></div>
</body>
</html>
The [[ ]] brackets are the new Symbols for angularJS. I will declare them in my angularJS files. The two way data-binding in combination with the name variable (Hello [[name]]) was used for the testing of angular and it works. I can ensure it is included properly.
This is my app.js
var guideApp = angular.module('guideApp', ['ngRoute']);
guideApp
.config([
'$routeProvider',
function($routeProvider) {
$routeProvider
.when('/guide/:guideId', {
controller: 'GuideDetailController',
templateUrl: '/static/templates/hearthstone_guides/guide-detail.html'
})
.otherwise({
redirectTo: '/'
});
}
])
.config([
'$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}
])
.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
});
and this is my controllers.js
var guideController = angular.module('guideController', []);
guideController.controller('GuideDetailController', [
'$scope',
'$routeParams',
'$http',
function($scope, $routeParams, $http) {
$http.get('http://10.0.3.162:8000/api/guides/' + $routeParams.guideId + '/?format=json')
.success(function(data) {
console.log('success');
$scope.guide = data;
})
.error(function(data, status) {
console.error(status, data);
});
}
]);
When I console.log('foo'); for instance between var guideController = angular.module('guideController', []); and guideController.controller('GuideDetailController', [... it works.
Unfortunately neither does console.log('success'); nor console.log(status, data); work.
Edit:
I changed the controller name now to GuideDetailController as you suggested but it still doesn't work.
This is the error marked in the firefox developer console:
"Error: [ng:areq] Argument 'GuideDetailController' is not a function, got undefined
http://errors.angularjs.org/1.3.20/ng/areq?p0=GuideDetailController&p1=not%20a nanunction%2C%20got%20undefined
minErr/<#http://10.0.3.162:8000/static/bower_components/angular/angular.js:63:12
assertArg#http://10.0.3.162:8000/static/bower_components/angular/angular.js:1590:1
assertArgFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:1600:1
$ControllerProvider/this.$get</<#http://10.0.3.162:8000/static/bower_components/angular/angular.js:8493:9
ngViewFillContentFactory/<.link#http://10.0.3.162:8000/static/bower_components/angular-route/angular-route.js:978:26
invokeLinkFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:8281:9
nodeLinkFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:7791:1
compositeLinkFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:7140:13
publicLinkFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:7019:30
createBoundTranscludeFn/boundTranscludeFn#http://10.0.3.162:8000/static/bower_components/angular/angular.js:7158:1
controllersBoundTransclude#http://10.0.3.162:8000/static/bower_components/angular/angular.js:7818:18
update#http://10.0.3.162:8000/static/bower_components/angular-route/angular-route.js:936:25
$RootScopeProvider/this.$get</Scope.prototype.$broadcast#http://10.0.3.162:8000/static/bower_components/angular/angular.js:14889:15
commitRoute/<#http://10.0.3.162:8000/static/bower_components/angular-route/angular-route.js:619:15
processQueue#http://10.0.3.162:8000/static/bower_components/angular/angular.js:13318:27
scheduleProcessQueue/<#http://10.0.3.162:8000/static/bower_components/angular/angular.js:13334:27
$RootScopeProvider/this.$get</Scope.prototype.$eval#http://10.0.3.162:8000/static/bower_components/angular/angular.js:14570:16
$RootScopeProvider/this.$get</Scope.prototype.$digest#http://10.0.3.162:8000/static/bower_components/angular/angular.js:14386:15
$RootScopeProvider/this.$get</Scope.prototype.$apply#http://10.0.3.162:8000/static/bower_components/angular/angular.js:14675:13
done#http://10.0.3.162:8000/static/bower_components/angular/angular.js:9725:36
completeRequest#http://10.0.3.162:8000/static/bower_components/angular/angular.js:9915:7
requestLoaded#http://10.0.3.162:8000/static/bower_components/angular/angular.js:9856:1
This is how my guide-detail.html file looks like
<h1>[[guide.title]]</h1>
<h1>{{guide.title}}</h1>
And this is the current results I get when I call this url http://10.0.3.162:8000/#/guide/1
You have put module name as a controller in the route config
Change From:
.config([
'$routeProvider',
function($routeProvider) {
$routeProvider
.when('/guide/:guideId', {
controller: 'guideController',
templateUrl: '/static/templates/hearthstone_guides/guide-detail.html'
})
.otherwise({
redirectTo: '/'
});
}
])
To:
config([
'$routeProvider',
function($routeProvider) {
$routeProvider
.when('/guide/:guideId', {
controller: 'GuideDetailController',
templateUrl: '/static/templates/hearthstone_guides/guide-detail.html'
})
.otherwise({
redirectTo: '/'
});
}
])
First, you should not use the minified versions of the libraries while developing.
Second, your unique route is configured to use the controller 'guideController'. But you have no such controller. The only controller defined is named 'GuideDetailController'.
'guideController' is not a controller. It's a module.

Unable to get value of route parameter from $routeParams

I'm working on an angularjs application that is having an "app.js" file. This file contains the following code:
var app = angular.module("myApp", ['ngRoute', 'ngCookies'])
app.config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
$routeProvider
.when('/UserProfileInfo/:UserId', {
templateUrl: 'Views/Users/UserProfileInfo.html',
controller: 'UserProfileInfoController'
})
.otherwise({
redirectTo: "/"
});
}]);
As you can see that above code is having a "UserProfileInfo" route that receives "UserId" route paramenter.
An html page is having a link tag referencing to the "UserProfileInfo" route and the code for this:
<a ng-href="#UserProfileInfo/{{item.UserId}}" ng-hide="hideViewUser" class="glyphicon glyphicon-trash" title="View"></a>
This link is referring to
www.somedomain.com/#/UserProfileInfo/131
The controller code for this UserProfileInfo view is below:
app.controller("UserProfileInfoController", ["$scope", "$location" "$routeParams", "$q", function ($scope, $location, $routeParams, $q) {
$scope.userProfileId = $routeParams.UserId;
}]);
The problem occurrs at this line:
$scope.userProfileId = $routeParams.UserId;
The UserId from $routeParams is coming undefined.
I have used all the required scripts on Index.html page:
<script src="Content/js/jquery-1.11.3.min.js"></script>
<script src="Content/js/bootstrap.min.js"></script>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="Scripts/angular-cookies.min.js"></script>
Kindly help me I'm missing anything.
Please help me in fixing this issue.
Thanks in advance.

Resources