$routeProvider not working properly in AngularJS (crashing the website) - javascript

I was following some random YT tutorial on using Angular's $routeProvider and the result - contrary to the video - is not working for me. Instead, what I get is crashed website and this error logged in Chrome's console: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.8/$injector/modulerr?p0=site&p1=Error%3A%20…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.8%2Fangular.min.js%3A41%3A249) By following the trail, I found that there's something wrong with `$routeProvider', but beats me if I know what. Here's my code:
var site = angular.module('site', []).
config(function($routeProvider){
$routeProvider.
when('/home', {template:'/pages/home.html'}).
when('/', {template:'/pages/home.html'}).
when('/in-play', {template:'/pages/in-play.html'}).
when('/popular', {template:'/pages/popular.html'}).
otherwise({redirectTo:'/home', tempalte:'/pages/home.html'});
});
function MainCtrl($scope, $location) {
$scope.setRoute = function(route) {
$location.path(route);
};
};
And here are all the HTMLs (I'm working with ng-include also):
<!DOCTYPE html>
<html ng-app="site">
<head>
<link rel="stylesheet" href="css/style.css">
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="scripts/app.js"></script>
<title>Pre-Demo</title>
</head>
<body ng-controller="mainStaysCtrl">
<header class="header" ng-include="'pages/header.html'"></header>
<nav class="nav" ng-include="'pages/nav.html'"></nav>
<div class="main">
<div class="left-col">
<div class="quick links" ng-include="'pages/quick_links.html'"> </div>
<div class="quick-inplay links" ng-include="'pages/quick_inplay_links.html'"></div>
<div class="winner links" ng-include="'pages/winner_links.html'"></div>
</div>
<div class="center-col" ng-controller="mainCtrl">
<div class="wraper" ng-view ng-controller="jsonCtrl"></div>
</div>
<div class="right-col">
<div class="expert-mixer" ng-include="'pages/mixer.html'"></div>
<div ng-include="'pages/twitter.html'"></div>
</div>
</div>
</body>
</html>
//included page that has the call for $routeProvider
<div class="events">
<div class="bullet">
<div class="bullet-padding">
<div ng-click="setRoute('in-play')" class="bullet-link">In-Play Links</div>
</div>
</div>
</div>
Could someone please tell me what's wrong?
EDIT
After Antiga's answer I got it to load the page. Everything besides the content that is to be loaded with ng-view and for which $routeProvider was set up in the first place. Here's the updated code:
var site = angular.module('site', ['ngRoute']).
config(function($routeProvider){
$routeProvider.
when('/home', {templateUrl:'/pages/home.html'}).
when('/', {templateUrl:'/pages/home.html'}).
when('/in-play', {templateUrl:'/pages/in-play.html'}).
when('/popular', {templateUrl:'/pages/popular.html'}).
otherwise({redirectTo:'/home', tempalteUrl:'/pages/home.html'});
});
site.controller('mainStaysCtrl', function($scope) {
$scope.setRoute = function(route) {
$location.path(route);
};
});
and HTML
<body ng-controller="mainStaysCtrl">
<header class="header" ng-include="'pages/header.html'"></header>
<nav class="nav" ng-include="'pages/nav.html'"></nav>
<div class="main">
<div class="left-col">
<div class="quick links" ng-include="'pages/quick_links.html'"></div>
<div class="quick-inplay links" ng-include="'pages/quick_inplay_links.html'"></div>
<div class="winner links" ng-include="'pages/winner_links.html'"></div>
</div>
<div class="center-col">
<div class="wraper" ng-view ></div>
</div>
<div class="right-col">
<div class="expert-mixer" ng-include="'pages/mixer.html'"></div>
<div ng-include="'pages/twitter.html'"></div>
</div>
</div>

You are not including the routing module.
Read up on this here so that you actually understand it first: https://docs.angularjs.org/api/ngRoute
Add this after you include angular.min.js:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
And then include the dependency in your main app module:
var site = angular.module('site', ['ngRoute']).

Okay, I got it working beyond Antiga's help.
There was few (yet minor) problems. I had to extend templateUrl path to include project folder.
when('/home', {templateUrl: '/ProjectName/pages/home.html', controller: 'mainStaysCtrl'}).
Other thing is that I simply forgot to include $location in controller.
site.controller('mainStaysCtrl', function($scope, $location) {
$scope.setRoute = function(route) {
$location.path(route);
};
});

Related

Unable to load the Module in Angularjs?

Hi I am developing Angularjs Application. I am using UI Router. This is my First Angular project and I am facing issues. I am running Index page. Index page contains header and footer. In body i am trying to bind views on page load.
Below is my Index.html
<html ng-app="RoslpApp">
<head>
<!--Angularjs and ui routing-->
<script data-require="angular.js#1.4.5" data-semver="1.4.5" src="https://code.angularjs.org/1.4.5/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.min.js"></script>
<!--Angularjs and ui routing-->
<!--Arebic Translation-->
<script data-require="angular-translate#*" data-semver="2.5.0" src="https://cdn.rawgit.com/angular-translate/bower-angular-translate/2.5.0/angular-translate.js"></script>
<script src="scripts/angular-translate.js"></script>
<script src="scripts/angular-translate-loader-partial.min.js"></script>
<!--Arebic Translation-->
<!--Date Picker-->
<link href="App/CSS/angular-datepicker.css" rel="stylesheet" />
<script src="App/JS/angular-datepicker.js"></script>
<!--Date Picker-->
<!--Toaster-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet">
<script src="https://unpkg.com/angular-toastr/dist/angular-toastr.tpls.js"></script>
<link rel="stylesheet" href="https://unpkg.com/angular-toastr/dist/angular-toastr.css" />
<!--Toaster-->
<!--SPA Files-->
<script src="App/App.js"></script>
<!--SPA Files-->
</head>
<body ng-controller="RoslpAppController">
<header>
<div class="logo"><img src="App/images/logo.png"></div>
</header>
<!--inject here-->
<div class="container">
<div ui-view></div>
</div>
<footer>
</footer>
This is my App.js
var app = angular.module('RoslpApp', ['pascalprecht.translate', 'ui.router', 'toastr', '720kb.datepicker']);
app.config(function ($stateProvider, $urlRouterProvider, $translateProvider, $translatePartialLoaderProvider)
{
$urlRouterProvider.otherwise('/HomePage');
$stateProvider
.state('ForgotPassword.ChangePasswords', {
url: '/ForgotPasswordChangePasswords',
templateUrl: 'ForgotPassword/ChangePassword.html',
params: {
LoginID: null
},
controller: 'ChangePasswords'
})
.state('HomePage', {
url: "/HomePage",
templateUrl: "Registration/HomePage.html"
});
});
app.controller('RoslpAppController', ['$scope', '$translate', 'toastr', function ($scope, $translate, toastr) {
//toastr.success('Hello world!', 'Toastr fun!');
$scope.clickHandler = function (key) {
$translate.use(key);
};
}]);
This is my HomePage.html
<div class="banner-container">
</div>
When i load my page first time, I am getting below error.
Uncaught Error: [$injector:nomod] Module 'RoslpApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
May I know why I am facing below mentioned issues. Thanks in advance.
There are no references in the index.html for pascalprecht.translate ,ui.router, 'toastr', '720kb.datepicker'
Add the necessary references. And the references to your app.js also missing!
You need to add your js script in your html
<html ng-app="RoslpApp">
<head>
</head>
<body ng-controller="RoslpAppController">
<header>
<div class="logo"><img src="App/images/logo.png"></div>
</header>
<!--inject here-->
<div class="container">
<div ui-view></div>
</div>
<footer>
</footer>
<script src="app.js"></script>
<script src="my_other_js.js"></script>
</body>
</html>

Getting an error in AngularJS

I am creating a small web app where I will show a chart of the top 10 popular TV shows. Then, When I go to the browser and inspect I get an error:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.6/$injector/unpr?p0=showProvider%20%3C-%20show%20%3C-%20MainController
<!doctype html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link href="css/main.css" rel="stylesheet" />
<!-- Angular JS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<body ng-app="Top10App">
<div class="header">
<div class="container">
10
</div>
</div>
<div class="main" ng-controller="MainController">
<div class="container">
<div class="content">
<!--TODO: Loop through shows and display each one with this HTML-->
<!--ng-repeat="show in shows" -->
<div>
<div class="rank">{{$index + 1}}</div>
<h2 class="series"> {{ index.series }}</h2>
<p class="genre">{{ index.genre }} </p>
<p class="run-start"> {{ index.run_start }}</p>
<p class="description"> {{ index.description }} </p>
</div>
</div>
</div>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/MainController.js"></script>
<!-- Services -->
<script src="js/services/show.js"></script>
</body>
</html>
Javascript
MainController.js
app.controller('MainController', ['$scope', 'show', function ($scope, show) {
show.success(function(data) {
$scope.show = data;
});
}]);
show.js
app.factory('Top10App', ['$http', function($http){
return $http.get('shows.json')
.success(function(data){
return data;
})
.error(function(err){
return err;
});
}]);
You're defining your service name as 'Top10App', so that's the way you should access it, not by the file name.
['$scope', 'Top10App', function ($scope, Top10App) { ...
Top10App.success(...
First, do you created the module? You should has something like:
// app.js
angular.module('app', []);
// maincontroller.js
angular.module('app').controller('myController, ...', [.......]);
// factory.js
angular.module('app').factory(...)
You are trying to inject show as a dependency for your controller, but it doesn't look like that is defined anywhere. That's why your error is telling you that it's an unknown provider.
I'm guessing you're trying to use your Top10App factory, so you need to inject it as such
app.controller('MainController', ['$scope', 'Top10App', function ($scope, Top10App) {
Top10App.success(...)
}

AngularJS: Browse page content not being displayed in Homepage

I'm a newbie to Angular and working on a project but I'm having an issue with displaying info in two different pages.
I have a browse page that displays profiles
I also have a homepage where I want to display the contents of the browse page plus other miscellaneous information.
To do that I created a component(browsePage)
Then I added the component to the home.view.html
<browse-page></browse-page>
but the profiles don't show up.
In my browse page the profiles do show up.
My code:
app.config.js
$routeProvider
.when('/home', {
RouteData: {
bodyStyle: {
//'background': 'url(../images/bg-7.jpg)repeat'
'background-color': 'white'
}
},
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
.when('/browse', {
RouteData: {
bodyStyle: {
//'background': 'url(../images/bg-10.jpg)repeat'
'background-color': 'white'
}
},
controller: 'BrowseController',
templateUrl: 'browse/browse.view.html',
controllerAs: 'vm'
})
home.controller.js
angular.module("mango").controller("HomeController", HomeController);
function HomeController() {
}
angular.module('mango').controller('ExampleController', ['$cookies', function($cookies) {
}]);
home.view.html
This is the home page<br>
Miscellaneous info goes here
<browse-page></browse-page>
Miscellaneous info goes here<br>
end of home page
browse.component.js
console.log("In browse.component.js");
angular.module("mango").component("browsePage",{
templateUrl:"browse/browse.view.html",
controller:BrowseController
});
browse.controller.js
angular.module("mango").controller("BrowseController", BrowseController);
BrowseController.$inject = ["$rootScope","$location","AuthenticationService","$http"];
function BrowseController($rootScope, $location, AuthenticationService, $http){
var vm = this;
$http.get('browse_profiles.json').success(function(data){
vm.data = data;
console.log("data==>");
console.log(data);
});
}
browse.view.html
<br><br>
<!-- Page Content -->
<div class="container">
<!-- Jumbotron Header -->
<header class="jumbotron hero-spacer" >
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>
</header>
<hr>
<!-- Page Features -->
<div class="row text-center">
<img id="mySpinner" src="/images/loader.gif" ng-show="loading" />
{{alpine}}
<div class="col-md-3 col-sm-6 hero-feature" ng-repeat="profile in vm.data">
<div class="thumbnail">
<img src="{{profile.thumbnail}}" alt="">
<div class="caption">
<div class="username-status">
<span class="username pull-left"><a ng-href="#/profile/{{profile.username}}">{{profile.username}}</a></span>
<p ng-class-odd="'circle odd'" ng-class-even="'circle even'"></p>
</div>
</div>
</div>
</div>
</div>
<!-- /.row -->
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © Your Website 2014</p>
</div>
</div>
</footer>
</div>
End of browse view.
<br><br>
index.html
<!doctype html>
<html lang="en" ng-app="mango">
<head>
<meta charset="utf-8">
<title>Mango</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="css/style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="bower_components/angular-cookies/angular-cookies.js"></script>
<script src="app.config.js"></script>
<script src="login/route-data.js"></script>
<script src="navigation_menu/navigation_menu.config.js"></script>
<script src="browse/browse.controller.js"></script>
<script src="browse/browse.component.js"></script>
<script src="home/home.controller.js"></script>
<script src="profile/profile.controller.js"></script>
<script src="settings/settings.controller.js"></script>
<script src="login/login.controller.js"></script>
<script src="login/app-services/authentication.service.js"></script>
<script src="login/app-services/flash.service.js"></script>
<script src="login/app-services/user.service.local-storage.js"></script>
</head>
<body ng-style="RouteData.get('bodyStyle')" ng-cloak>
<navigationmenu ng-if="location.path() !== '/login'"></navigationmenu>
<ng-view autoscroll></ng-view>
</body>
</html>
I'm not getting any errors in the console.You can ignore the GET error.
What do I need to do to fix my problem?
I'm starting to think th
Thanks in advanced.
I think in your component, you haven't specified controllerAs, when you goto /browse, your browseView.html is getting the controller instance as vm, but when browseView.html is loaded through component,it is not getting the controller instance, as it is not getting instantiated like it is done, in routeProvider.
Try doing,
angular.module("mango").component("browsePage",{
templateUrl:"browse/browse.view.html",
controller:BrowseController,
controllerAs: 'vm'
});
Hope, this solves the issue.

Angular ui-router doesn't work

I'm new to Angular, i've been trying to use ui-router in this project, but ui-view doesn't show anything, did i miss something?.
I'm trying to build a mean app, the folder structure is the following:
The app folder is where the angular app is located.
<!DOCTYPE html>
<html lang="en" ng-app="TimeWaste">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
</head>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="">
<input type="text" ng-model="login.email">
<input type="password" ng-model="login.password">
<button>Login</button>
<a ui-sref="signUp">Create an account</a>
</div>
</div>
</nav>
<body>
<div ui-view></div>
</body>
<script src="node_modules/angular/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
<script src="app/app.js"></script>
<script src="app/signup/signup-controller.js"></script>
</html>
this is the app.js
(function()
{
angular.module('TimeWaste',['ui.router'])
.config(function($stateProvider)
{
$stateProvider
.state('signup',{
url:"/signup",
templateUrl: "app/signup/signup.html",
controller:"SignupController"
})
})
}());
the signup.html view
<div class="row">
<div class="col-sm-6">
<div class="row">
<strong>Email Address:</strong>
<input type="text" ng-model="newUser.email" class="form-control">
</div>
<div class="row">
<strong>Password:</strong>
<input type="password" ng-model="newUser.password" class="form-control">
</div>
<button ng-click="createUser()">Submit</button>
</div>
</div>
and the signup controller
(function()
{
angular.module('TimeWaste')
.controller('SignupController', ['$scope','$state',function($scope,$state){
}]);
}());
It may typo and path missing !!
in html used <a ui-sref="signUp">Create an account</a> but in $stateProvider used signup so need to change signUp to signup.
and I assume your app.js is in app directory because you use
<script src="app/app.js"></script> in home page.
if right then your template path need to change templateUrl: "signup/signup.html",
However you can configure ui.route to be case insensitive.
like:
.config(function($stateProvider,$urlMatcherFactoryProvider,)
{
$urlMatcherFactoryProvider.caseInsensitive(true);
$urlMatcherFactoryProvider.strictMode(false);
$stateProvider
.state('signup',{
url:"/signup",
templateUrl: "signup/signup.html",
controller:"SignupController"
})
})

Call directive from ng-click of element inside a partial in AngularJS

I have the following HTML:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body ng-app="myApp">
<div class="container">
<div ng-view=""></div>
</div>
<!--Core JS Libraries-->
<script src="js/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/angular-route.min.js"></script>
<!--Core UI Library-->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
//Define an angular module for our app
var myApp = angular.module('myApp', ['ngRoute']);
//Define Routing for app
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'pages/View1.html',
controller: 'HomeController'
}).
when('/design', {
templateUrl: 'pages/2.html',
controller: 'DesignController'
}).
otherwise({
redirectTo: '/home'
});
}]);
var controllers = {};
controllers.HomeController = function ($scope) {
$scope.GetView2 = function ($scope) {
$('#one').hide();
$('#two').show();
myApp.directive('myDirective', function () {
return {
restrict: 'E',
templateUrl: 'pages/view2.html'
}
});
};
};
controllers.DesignController = function ($scope) {
};
//adding the controllers to myApp angularjs app
myApp.controller(controllers);
</script>
</body>
</html>
And my View1.html:
<button ng-click="GetView2()">Get View 2</button>
<br />
<div class="row" id="one">
<h1>View 1</h1>
</div>
<div class="row" id="two" style="display: none;">
<h1>View 2</h1>
<!--change the display to block and load partial here on above button click-->
<my-directive></my-directive>
</div>
And View2.html:
<h3>Something in View2</h3>
Now,when I run the HTML, on Button click, View 1 heading chanegs to View 2 heading, so my routing and GetView2() function calls are working. But my <my-directive> is not getting updated with View2.html which I am calling in the directive in templateUrl.
I am new to AngularJS and trying to use ng-view and directives for multiple views type of scenario. I have read that I should avoid nested views, and implement directives, but I am not getting how to implement such a simple scenario.
I can easily replace content of Div with id="two" using jQuery, but I am trying to do it in proper angularjs way.
There are better ways to achieve what you are trying.
First this
$('#one').hide();
$('#two').show();
should be avoided as this is direct DOM manipulation from Controller.
You should use or ng-show directive to show hide the element.
<div class="row" id="one" ng-show="currentView='one'">
<h1>View 1</h1>
</div>
<div class="row" id="two" ng-show="currentView='two'">
</div>
The controller should be
$scope.GetView2 = function ($scope) {
$scope.currentView='two';
}
For the directive that you have created can be done by ng-include such as
<ng-include src='pages/view2.html' />
and make sure there is a view at this path.

Categories

Resources