Angular template routing doesn't work - javascript

I'd like to load a template html in my main index.html when I view my angular project but I always get an empty screen.
<!DOCTYPE html>
<html lang="nl" ng-app="store">
<head>
<meta charset="UTF-8">
<title>NMDAD-II Web App</title>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body class="bg-darkRed" ng-controller="StoreController as store">
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-route.min.js"></script>
<script src="vendor/angular/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/main.js"></script>
<script src="app/app.js"></script>
<script type="text/javascript">
angular.module("store", ["ngRoute"])
.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'app/home/home.view.html'
})
.otherwise({
redirectTo: '/'
});
});
</script>
<script id="__bs_script__">//<![CDATA[
document.write("<script async src='http://HOST:3000/browser-sync/browser-sync-client.2.11.2.js'><\/script>".replace("HOST", location.hostname));
//]]></script>
</body>
</html>
I've also tried to load it with browser sync but it's still the same. I want to load home.view.html in my index.html. I tried to write the javascript in app.js but that still didn't work.
EDIT: this is my app.js. my main.js just contains some jquery
function () {
'use strict';
// Module declarations
angular.module('store', [
// Angular Module Dependencies
// ---------------------------
'ngAnimate',
'ngMaterial',
'ngMessages',
'ngResource',
// Third-party Module Dependencies
// -------------------------------
'ui.router', // Angular UI Router: https://github.com/angular-ui/ui-router/wiki
// Custom Module Dependencies
// --------------------------
'store.home',
'store.services'
]);
angular.module('store.home', []);
angular.module('store.services', []);
// Make wrapper services and remove globals for Third-party Libraries
angular.module('store')
.run(Run);
function Run(
$_,
$faker
) {}
var app = angular.module('store',[]);
app.controller('StoreController', function(){
this.products = gems;
});
var gems = [
{
title: "Islay Blended Malt",
description: "The Isle of Islay is known for its peaty whiskies. For there is a great abundance of peat on the island, and because electricity reached Islay so late, peated was relied upon as a staple source of fuel. But there is so much than just peat to be found.",
price: "103.45",
canPurchase: true
},
{
title: "Springbank 10 Year old",
description: "Blended from a mixture of bourbon and sherry casks, the light colour of this malt belies the richness of its character.",
price: "36.25",
canPurchase: true
},
{
title: "Hazelburn 10 Year old",
description: "First released in 2014, this is the first bottling of Hazelburn at 10 years of age. Hazelburn is Springbank's triple-distilled, unpeated single malt.",
price: "37.75",
canPurchase: true
}
]
})();

The problem I see is you are loading angular-route before you load angular.
Try switching those two lines to:
<script src="vendor/angular/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-route.min.js"></script>
I get this error ReferenceError: angular is not defined when I load the scripts how you are loading them.

Related

Keep getting AngularJS module not available (ASP.NET 5)

Trying to get simple Angular DI working in an existing ASP.NET 5 (Core) project.
Been following this tutorial.
Versions:
AngularJS 1.4.6
ASP.NET 5 (vNext)
Visual Studio 2015
Windows 10
Checked all the basic gotchas with naming and so on. Unclear about how my dependent js-files "controllers.js" & "services.js" are suppose to be discovered by Angular?
If I explicitly include them - which by the tutorial shouldn't be required - I still get
[ng:areq] Argument 'customerController' is not a function, got
undefined
Index.html
<!DOCTYPE html>
<html ng-app="bonusapp">
<head>
<meta charset="utf-8" />
<link href="lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="lib/bootswatch/yeti/bootstrap.min.css" rel="stylesheet" />
<link href="css/main.css" rel="stylesheet" />
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript" src="lib/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.js"></script>
<script src="lib/app.js"></script>
<!--<script>angular.bootstrap(document, ['app']);</script>-->
</head>
<body ng-cloak>
<div id="wrapper" ng-controller="customerController">
<div id="main" class="container-fluid">
<div class="row">
<div class="col-md-3">
<h2>Kunder</h2>
<ul>
<li ng-repeat="item in Models">
{{item.FirstName}} {{item.LastName}} <a>Redigera</a> <a>Radera</a>
</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" src="lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="lib/jquery-validation/dist/jquery.validate.js"></script>
<script type="text/javascript" src="lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</body>
</html>
app.js
(function () {
'use strict';
// Define module "app"
angular.module('bonusapp', [
// Angular modules
'ngRoute',
'ngResource',
// Custom modules
'customerService'
// 3rd Party Modules
]);
})();
controllers.js
(function () {
'use strict';
// Assign controller to app
angular
.module('bonusapp')
.controller('customerController', [
customerController]);
// $inject() method call is required to enable the controller to work with minification.
customerController.$inject = [
'$scope',
'Customers'
];
// Construct controller
function customerController($scope, Customers) {
// Populate model from service
$scope.Models = Customers.get();
}
})();
services.js
(function() {
'use strict';
var customerService =
angular
.module('customerService', ['ngResource']);
customerService
.factory('Customers',
['$resource'],
function ($resource) {
return $resource('/api/customers', {}, {
// Service call to get Customers
get: {
method: 'GET',
params: {},
isArray: true
}
});
}
);
})();
As Win suggested, I needed to:
Fix the include order to put jQuery first
Include all my JS files
But I still had some issues. For reference, here are the fixed scripts:
controller.js
(function () {
'use strict';
// Construct controller
// Remarks: controller is now declared FIRST
var customerController = function ($scope, Customers) {
$scope.Title = "Title";
// Populate model from service
$scope.Models = Customers.get();
}
// $inject() method call is required to enable the controller to work with minification.
customerController.$inject = [
'$scope',
'Customers'
];
// Assign controller to app
angular
.module('bonusapp')
.controller('customerController',
customerController);
})();
services.js
(function() {
'use strict';
var customerService =
angular
.module('customerService',
['ngResource']);
customerService
.factory('Customers',
['$resource',
function ($resource) {
return $resource('/api/customers', {}, {
// Service call to get Customers
// Remarks: 'get' in single quotes
'get': {
method: 'GET',
params: {},
isArray: true
}
});
}
]);
})();
You need to include controller.js and services.js files.
In addition, you need to move jquery before angular.js.
<script type="text/javascript" src="lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript" src="lib/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.js"></script>
<script src="lib/app.js"></script>
<script src="lib/controllers.js"></script>
<script src="lib/services.js"></script>
FYI: You might also want to look into bundling and magnification, before you publish.

$compile:tpload Failed to load template (HTTP status: 404) happens in one sub url only

I am trying to run my angularjs-based app on local file throughout File transfer protocol(not on any server).
My project contains html files as
index.html and template folder on the top level, and other sub html files, such as common.html, main.html, etc. which are included in the template folder.
This app triggers the error below,
Error: [$compile:tpload] Failed to load template: template/common.html (HTTP status: 404),
only when entering through File transfer, file:///C:/Webapp/index.html#common/abc.
But it does not happen when entering by http.
Also, this file transfer access triggers an error in Chrome, IE, but not in Firefox.
And the second odd thing is that this happens only when url ends with #common/abc.
The only one url that triggers the tpload error goes like
file:///C:/Webapp/index.html#common/abc (case only with #common/~ after index.html, and I don't get the error if it doesn't has 'abc' at the last).
The 'abc' functions like parameters(called channelTag on my project) going to be input on my App, not actual files.
And This project intends to start with the url file:///C:/Webapp/index.html#common/abc which gets the channelTag, and flows
other sub urls.
Other urls like file:///C:/Webapp/index.html#main, or file:///C:/Webapp/index.html#sub2 are okay. No errors are shown there.
After checking some related answers on searching,
most of the answers say to include bootstrap-tpls.js instead of bootstrap.js, but this method shows the same result.
Attached are the html and javascript code below :
index.html:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="EUC-KR">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="{{metaservice.metaViewport()}}" />
<title>BtvWebApp</title>
<link rel="stylesheet" type="text/css" href="css/btv.css">
<script src="js/lib/jquery-1.11.1.min.js"></script>
<script src="js/bxslider/jquery.bxslider.min.js"></script>
<script src="js/lib/angular.js"></script>
<script src="js/bootstrap/bootstrap.js"></script>
<script src="js/lib/angular-route.min.js"></script>
<script src="js/lib/angular-sanitize.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script>
<script src="js/app.js"></script>
<script src="js/lib/script.js"></script>
<script src="js/view/main/mainController.js"></script>
<script src="js/view/commonController.js"></script>
<script src="js/filters/zerofillFilter.js"></script>
<script src="js/config/constants.js"></script>
<script src="js/config/messages.js"></script>
</head>
<body>
<ng-view></ng-view>
</body>
</html>
common.html is an empty html file.
app.js:
var app = angular.module('myApp', [
'ngRoute',
'ngSanitize',
'myApp.constant',
'myApp.messages'
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/main', {
templateUrl: 'template/main.html',
controller: 'mainCtrl'
})
// Containing other sub whens...
/////////////////////////////
.otherwise({redirectTo: '/common/:channelTag'});
}]);
commonController.js:
'use strict';
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/common/:channelTag', {
templateUrl: 'template/common.html',
controller: 'commonCtrl'
});
}])
.controller('commonCtrl', ['$scope', '$location', '$http', '$rootScope', '$routeParams', 'commonConstant', 'information', 'Utils', 'MetaService'
, function($scope, $location, $http, $rootScope, $routeParams, commonConstant, information, Utils, MetaService) {
$scope.isDataLoading = true;
var channelTag = $routeParams.channelTag;
if(!Utils.isEmpty(channelTag)){
information.channelTag = channelTag;
}
}])
.service('MetaService', function() {
var metaViewport = '';
return {
set: function(newViewport) {
metaViewport = newViewport;
},
metaViewport: function() { return metaViewport; }
}
});
What is the problem when running through file transfer protocol even I set the chrome option with disable-security?
And why I get the error only when the url ends with '~#common/abc' ?
Any suggestions are welcome, please.
Including ui.bootstrap.tpls in your project will fix above issue
Oops, I solved this problem myself.
It was due to common.html with empty code, so some browsers could not find the template contents. Adding a <div> tag in that file, no error found.
Wish it be helping someone...

AngularJS module doesn't work

So I've been looking at this for way too long. Really hope someone could help me out :) I'm just trying to create a module that creates a directive and controller for my site header in AngularJS. I don't get any error and the log in my code won't show up. This is the code related to the header module:
header/header.js
'use strict';
angular.module('myApp.header', [])
.directive("headerBar", [function(){
return {
restric: "E",
templateUrl: "header/header.html",
controller: 'HeaderCtrl'
};
}])
.controller('HeaderCtrl', ['$log', function($log) {
$log.log('test header controller');
}]);
app.js
angular.module('myApp', [
'ngRoute',
'myApp.header'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/'});
}]);
index.html
<script src="header/header.js"></script>
<header-bar></header-bar>
I see a typo on your directive definition:
Should be restrict: "E", you're currently missing the 't'
You need to call the app.js and angular.js reference scripts in your index page
Some think like below
//Jquery Scripts
//Angular.js library scripts
<script src="header/header.js"></script>
**<script src="app.js"></script>**// Please refer here your app.js script
<header-bar></header-bar>
This works for me.Please check that you are including all files.
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="header/header.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="myApp.header" ng-controller="HeaderCtrl">
<header-bar></header-bar>
</body>
</html>

Angular module error

i try to write an angular app using best code practice and i got to this:
index.html file contain :
<!DOCTYPE html>
<html ng-app='hrsApp'>
<head>
<title>Hrs app</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body ng-controller="homeCtrl">
<div class='container'>
<div ng-view></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular-route.min.js"></script>
<script src='app.js'></script>
<script src='js/controllers/homeCtrl.js'></script>
<script src='js/controllers/avCtrl.js'></script>
</body>
</html>
Main file: app.js:
angular.module('home', []);
angular.module('av', []);
// Declare app level module which depends on filters, and services
angular.module('hrsApp', [
'hrsApp.controllers',
'hrsApp.services',
'hrsApp.directives',
'hrsApp.filters',
// AngularJS
'ngRoute',
// All modules are being loaded here but EMPTY - they will be filled with controllers and functionality
'home',
'av'
]);
// configure our routes
angular.module('hrsApp').config([
'$routeProvider',
function ($routeProvider) {
'use strict';
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'views/home.html',
controller: 'homeCtrl'
})
// route for the about page
.when('/av', {
templateUrl: 'views/av.html',
controller: 'avCtrl'
})
// route for the contact page
.otherwise({
redirectTo: '/'
});
}
]);
Then i added the home controller:
/*global angular*/
angular.module('home').controller('homeCtrl', [
'$scope',
function ($scope) {
'use strict';
$scope._init = function () {
$scope.message = "welcome to Home Ctrl";
};
// DESTRUCTOR
$scope.$on('$destroy', function () {
});
// Run constructor
$scope._init();
$scope.log('info', '[HomeCtrl] initialized');
}
]);
and home template that for the moment contain only a binding to the message variable:
<div>{{message}}</div>
When i try to run the application i got : Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.0/$injector/modulerr?p0=hrsApp&p1=Error%3A%…googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.0%2Fangular.min.js%3A18%3A3) angular.js:38
Any idea what i do wrong?
From your code I can see that you have injected modules that you did not declared.
in order todo so you must add the following lines to your code:
angular.module('hrsApp.controllers',[]);
angular.module('hrsApp.services',[]);
angular.module('hrsApp.directives',[]);
angular.module('hrsApp.filters',[]);

moving from ng-include to ngRoute

I am new to Angular and learned the basics about it recently.
In my current project, I am developing a single page application. As of now, my HTML/JS setup is as per below:
HTML:
<body>
<ng-include src='"src/includes/home.html"'></ng-include>
<!-- home.html is the HTML template with static data -->
</body>
app.js:
'use strict';
var app = angular.module('MyApp',['home']);
angular
.module('home', [])
.directive('homeDir', function(){
return {
replace: true,
restrict: 'E',
templateUrl: 'src/includes/home.html'
};
});
This code is working fine but I would like to introduce routing to have better control over the pages, instead of using ng-include.
So now, my HTML looks the same and I actually dont know what to change in it while using routing.
My app.js now looks like this:
'use strict';
var app = angular.module('MyApp',['home']);
// trying to introduce routing:
angular
.module('home', ['ngResource', 'ngRoute'])
.config(['$routeProvider', '$locationProvider'],
function($routeProvider, $locationProvider){
$routeProvider.
when('/', {
templateUrl: 'src/includes/home.html',
controller: 'homeCtrl'
}).
when('/drawer', {
redirectTo: 'src/includes/home.html#drawer',
controller: 'drawerCtrl'
})
.otherwise({
redirectTo: '/'
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
}
);
app.controller('homeCtrl', function($scope){
$scope.message = "some message";
console.log("homeCtrl called");
});
app.controller('drawerCtrl', function($scope){
$scope.message = "some other message";
console.log("drawerCtrl called");
});
However, I am getting an error:
Error: error:modulerr
Module Error
As per the link following the error:
This error occurs when a module fails to load due to some exception.
Why is it not loading? What am I missing? What should I change the HTML to?
UPDATE:
After including angular-route.min.js, I am getting the error:
Error: whole is undefined
beginsWith#file:///D:/projects/svn/trunk/src/libs/angular.js:8729:1
LocationHtml5Url/this.$$parse#file:///D:/projects/svn/trunk/src/libs/angular.js:8772:9
$LocationProvider/this.$get<#file:///D:/projects/svn/trunk/src/libs/angular.js:9269:5
invoke#file:///D:/projects/svn/trunk/src/libs/angular.js:3762:7
createInjector/instanceCache.$injector<#file:///D:/projects/svn/trunk/src/libs/angular.js:3604:13
getService#file:///D:/projects/svn/trunk/src/libs/angular.js:3725:11
invoke#file:///D:/projects/svn/trunk/src/libs/angular.js:3752:1
createInjector/instanceCache.$injector<#file:///D:/projects/svn/trunk/src/libs/angular.js:3604:13
getService#file:///D:/projects/svn/trunk/src/libs/angular.js:3725:11
invoke#file:///D:/projects/svn/trunk/src/libs/angular.js:3752:1
registerDirective/</<#file:///D:/projects/svn/trunk/src/libs/angular.js:5316:21
forEach#file:///D:/projects/svn/trunk/src/libs/angular.js:322:7
registerDirective/<#file:///D:/projects/svn/trunk/src/libs/angular.js:5314:13
invoke#file:///D:/projects/svn/trunk/src/libs/angular.js:3762:7
createInjector/instanceCache.$injector<#file:///D:/projects/svn/trunk/src/libs/angular.js:3604:13
getService#file:///D:/projects/svn/trunk/src/libs/angular.js:3725:11
addDirective#file:///D:/projects/svn/trunk/src/libs/angular.js:6363:28
collectDirectives#file:///D:/projects/svn/trunk/src/libs/angular.js:5801:1
compileNodes#file:///D:/projects/svn/trunk/src/libs/angular.js:5666:1
compileNodes#file:///D:/projects/svn/trunk/src/libs/angular.js:5682:1
compileNodes#file:///D:/projects/svn/trunk/src/libs/angular.js:5682:1
compile#file:///D:/projects/svn/trunk/src/libs/angular.js:5603:1
bootstrap/doBootstrap/</<#file:///D:/projects/svn/trunk/src/libs/angular.js:1343:11
$RootScopeProvider/this.$get</Scope.prototype.$eval#file:///D:/projects/svn/trunk/src/libs/angular.js:12077:9
$RootScopeProvider/this.$get</Scope.prototype.$apply#file:///D:/projects/svn/trunk/src/libs/angular.js:12175:11
bootstrap/doBootstrap/<#file:///D:/projects/svn/trunk/src/libs/angular.js:1341:9
invoke#file:///D:/projects/svn/trunk/src/libs/angular.js:3762:7
bootstrap/doBootstrap#file:///D:/projects/svn/trunk/src/libs/angular.js:1340:8
bootstrap#file:///D:/projects/svn/trunk/src/libs/angular.js:1353:5
angularInit#file:///D:/projects/svn/trunk/src/libs/angular.js:1301:37
#file:///D:/projects/svn/trunk/src/libs/angular.js:21050:5
jQuery.Callbacks/fire#file:///D:/projects/svn/trunk/src/libs/jquery-1.9.1.min.js:1037:1
jQuery.Callbacks/self.fireWith#file:///D:/projects/svn/trunk/src/libs/jquery-1.9.1.min.js:1148:7
.ready#file:///D:/projects/svn/trunk/src/libs/jquery-1.9.1.min.js:433:38
completed#file:///D:/projects/svn/trunk/src/libs/jquery-1.9.1.min.js:103:4
file:///D:/projects/svn/trunk/src/libs/angular.js
Line 9511
Edit:
Here are my HTML imports:
<head>
<title></title>
<!-- External libraries -->
<link rel="stylesheet" type="text/css" href="src/css/font-awesome-4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="src/css/headers.css">
<link rel="stylesheet" type="text/css" href="src/css/drawer.css">
<link rel="stylesheet" type="text/css" href="src/css/custom.css">
<script type="text/javascript" src="src/libs/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="src/libs/bootstrap.min.js"></script>
<script type="text/javascript" src="src/libs/angular.js"></script>
<script type="text/javascript" src="src/libs/angular-resource.js"></script>
<script type="text/javascript" src="src/libs/angular-ui-router.js"></script>
<script type="text/javascript" src="src/libs/angular-sanitize.min.js"></script>
<script type="text/javascript" src="src/libs/angular-pull-to-refresh.js"></script>
<script type="text/javascript" src="src/libs/nprogress.js"></script>
<script type="text/javascript" src="src/libs/ng-modal.js"></script>
<script type="text/javascript" src="src/libs/angular-route.min.js"></script>
<script type="text/javascript" src="src/js/jssor-slider-plugin/jssor.core.js"></script>
<script type="text/javascript" src="src/js/jssor-slider-plugin/jssor.utils.js"></script>
<script type="text/javascript" src="src/js/jssor-slider-plugin/jssor.slider.js"></script>
<script type="text/javascript" src="src/js/app.js"></script>
<script>
document.write('<base href="' + document.location + '" />');
</script>
</head>
Config section is incorrect. Instead of
.config(['$routeProvider', '$locationProvider'], function($routeProvider, $locationProvider) { ... });
it should be
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { ... }]);
Note, that function definition belongs to array object.
Another mistake is in redirectTo property of the drawer route, currently it doesn't make sense. You want probably this instead:
.when('/drawer', {
templateUrl: 'src/includes/drawer.html',
controller: 'drawerCtrl'
})
Ensue that you have added the angular-route.js file to the html file.
And you are missing the ngRoute module here -
var app = angular.module('MyApp',['ngRoute','ngResource' ]);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){... }]);
dfsq is correct. There are syntax errors in the code.

Categories

Resources