AngularJS and Angular-Route-Segment - angularjs

I am new to AngularJS so any tips will be welcome as I'm still trying to wrap my head around how everything works.
The following controller houses other controllers inside of it, however I've shortened the code to replicate my problem without the inner segments (I'll have more bugs once I add that in).
This is my html section:
<div ng-app="app">
<div class="ng-cloak" ng-controller="mainController">
<a ng-class="{active: ('sectionHome' | routeSegmentStartsWith)}" href="#{{'sectionHome' | routeSegmentUrl}}">Home</a>
<div id="content" style="">
<div app-view-segment="0"></div>
</div>
<div id=loading class=alert ng-show="loader.show">Loading...</div>
</div>
</div>
And the javascript:
var app = angular.module('app', ['ngRoute', 'ngAnimate', 'route-segment', 'view-segment']);
app.config(function($routeSegmentProvider, $routeProvider) {
$routeSegmentProvider.options.autoLoadTemplates = true;
$routeSegmentProvider
.when('/Home', 'sectionHome')
.segment('sectionHome', {
'default': true,
templateUrl: '../templates/sHome.html',
controller: 'mainController'})
$routeProvider.otherwise({redirectTo: '/Home'});
}) ;
app.value('loader', {show: false});
app.controller('mainController', function($scope, $routeSegment, loader) {
$scope.$routeSegment = $routeSegment;
$scope.loader = loader;
$scope.$on('routeSegmentChange', function() {
loader.show = false;
})
});
I'm either missing something conceptual or some other big thing, since when I inspect the link it appears that the scope bindings are not set in the html document and I remain with "ng-class="{active: ('sectionHome' | routeSegment...".
I've tried editing the code in jsFiddle (http://jsfiddle.net/3boccdu6/) however there I'm receiving an error
"..[$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it.."
This would make sense but I'm really not sure what I'm doing wrong, I've been following this working example:
http://angular-route-segment.com/src/example/#/section3

Adding the following to your html will resolve the issue.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-resource.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-route.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-route-segment/1.4.0/angular-route-segment.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-animate.min.js">
</script>
<script src="app.js"></script>

Related

Angularjs Multiple modules

I am writing a website and I need two AngularJs modules: ngRoute and ui.bootstrap.
Now, my script for ngRoute is
var ngRouteApp=angular.module('ngRouteApp',["ngRoute"]);
ngRouteApp.config(['$routeProvider', function($routeProvider){
$routeProvider
... some stuff here ...
}]);
while for bootstrap is
var bootstrapApp = angular.module('bootstrapApp', ['ui.bootstrap']);
bootstrapApp.controller('CarouselCtrl', CarouselCtrl);
function CarouselCtrl($scope){
...some stuff here...
};
Now I suppose I could combine the two
angular.module("allApps", ["ngRouteApp", "bootstrapApp"]);
and into the HTML I can write
<html ng-app="allApps">
but if I do, it doesn't work. I can't see anything.
Define an angular module with all the dependences you need.
var app = angular.module('allApps',['ngRoute', 'ui.bootstrap'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
... some stuff here ...
}]);
Then use var appto define controllers.
app.controller('CarouselCtrl', [ '$scope', function ($scope){
...some stuff here...
}]);
html
<html ng-app="allApps">
user3130401 is correct, thats the proper way to do it, however, you haven't included ngRoute in your html page. Running your plunkr the console prints:
Uncaught Error: [$injector:modulerr] Failed to instantiate module allApps due to:
Error: [$injector:modulerr] Failed to instantiate module ngRoute due to:
Error: [$injector:nomod] Module 'ngRoute' is not available!
As soon as you add the ng-route code, it works fine.
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
Here is your working example.
I separated the apps as you wanted using best practices.
As you will see i'm not using the appvariable as a don't consider it best practice. Whatever you place in a javascript file outside of an iffy function is made public. That's why i prefer to use iffy functions and place all angular definitions together at the end of the file.
Also note in index.html the order i place the scripts.
<script src="ngRouteApp.js"></script>
<script src="app.js"></script>
app.js
(function(angular) {
"use strict";
function carouselDemoCtrl($scope) {
var vm = $scope;
vm.myInterval = 3000;
vm.noWrapSlides = false;
vm.activeSlide = 0;
vm.slides = [{
image: 'http://lorempixel.com/400/200/'
}, {
image: 'http://lorempixel.com/400/200/food'
}, {
image: 'http://lorempixel.com/400/200/sports'
}, {
image: 'http://lorempixel.com/400/200/people'
}];
}
carouselDemoCtrl.$inject = ["$scope"];
angular
.module("allApps", ["ngRoute", "ui.bootstrap"])
.controller("carouselDemoCtrl", carouselDemoCtrl);
})(angular);
ngRouteApp.js
(function(angular) {
"use strict";
function configs($routeProvider) {
$routeProvider
.when('/', {
template: ''
})
.when('/gallery', {
templateUrl: 'pages/gallery.html'
})
.when('/actorBio', {
templateUrl: 'pages/actorBio.html'
})
.when('/contatti', {
templateUrl: 'pages/contatti'
})
.otherwise({
redirectTo: '/'
});
}
configs.$inject = ["$routeProvider"];
angular
.module("ngRouteApp", ["ngRoute"])
})(angular);
index.html
<!doctype html>
<html ng-app="allApps">
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-route.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.2.1.js"></script>
<script src="ngRouteApp.js"></script>
<script src="app.js"></script>
</head>
<body>
<div>
Write your name here
<input type="text" ng-model="name"> Hi {{name}} Those are your photos:
<div ng-controller="carouselDemoCtrl" id="slides_control">
<div>
<uib-carousel active="active" interval="myInterval">
<uib-slide ng-repeat="slide in slides" index="$index">
<img ng-src="{{slide.image}}" style="margin:auto;">
<div class="carousel-caption">
<h4>Slide {{$index+1}}</h4>
</div>
</uib-slide>
</uib-carousel>
</div>
</div>
</div>
</body>
</html>

angular - Switch navbar when view is changed

I am using angular-route.min.js and I have two designs for my navbar.
The First one is the landing page navbar that will appear first on my index.html.
The second navbar is when the user is routed to the /signin page.
I am unsure on how to go about this. I see a lot of different ways that this could be done, but none really that explain how I could change the entire header view when another route is chosen. They just show how to change the links that are contained inside of it. Like this Stack
how can I switch out the header when it is routed to the /signin page?
also, I am working with another person who is doing the backend with Django. That is why I changed the "{{ }}" to "[[ ]]".
var app = angular.module('app', ['ui.bootstrap', 'ngRoute']);
app.config(function($interpolateProvider, $routeProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
$routeProvider
.when('/', {
templateUrl: 'pages/LandingPage.html',
})
.when('/signin', {
templateUrl: 'pages/SignIn.html'
})
.when('/contact', {
templateUrl: 'pages/contact.html'
});
});
<!DOCTYPE html>
<html lang="en" data-ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js">
</script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-route.js">
</script>
</head>
<body>
<div ng-view></div>
</body>
</html>
I think ng-include directive could solve the situation you are facing.
In controller code.
.controller('HeaderCtrl', function($scope, $location) {
$scope.$on('$locationChangeSuccess', function(/* EDIT: remove params for jshint */) {
var path = $location.path();
//EDIT: cope with other path
$scope.templateUrl = (path==='/signin' || path==='/contact') ? 'template/header4signin.html' : 'template/header4normal.html' ;
});
})
In Html.
<body>
<div ng-controller="HeaderCtrl">
<div ng-include="templateUrl"></div>
</div>
<div ng-view></div>
</body>
I hope this could help you. :)
The difference of your two navbars are not significant. An alternative is just use ng-class and ng-show to give different styles.
For example, in the navbar.html:
<nav>
<span ng-show="isNormalPage">Inn</span>
<img ng-class="{align-center: isNormalPage}">Logo</img>
<span ng-show="isNormalPage">Sing in</span>
</nav>
In your JS file, add a flag to mark singin page:
.when('/signin', {
controller: [$scope, function ($scope) {
$scope.isNormalPage = false;
};
}]
})

Angularjs routing not working

Everything worked fine until I tried to add routing. I read that Angularjs version 1.2+ requires 'ngRoute' as an dependency (I am using version 1.2.16). I added it but it still doesn't work. Below are my codes.
test.html (Main Page)
<html ng-app="demoApp">
<head>
<title></title>
</head>
<body>
<p>Front Page</p>
<div ng-view></div>
<script src="angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.js"></script>
<script src="testjs.js"></script>
</body>
</html>
testjs.js
demoApp = angular.module('demoApp',['ngRoute']);
demoApp.config(function ($routeProvider) {
$routeProvider.when('/', {
controller: 'SimpleController',
templateUrl: '/partials/first.html'
});
});
var controllers = {};
controllers.SimpleController = function ($scope){
$scope.first = "Info";
$scope.customers=[
{name:'jerry',city:'chicago'},
{name:'tom',city:'houston'},
{name:'enslo',city:'taipei'}
];
};
demoApp.controller(controllers);
first.html
<div>
<input type="text" ng-model="name"/>
</br>
{{first}}
</br>
<ul>
<li ng-repeat="cust in customers | filter:name">{{cust.name | uppercase}} - {{cust.city}}</li>
</ul>
</div>
Here is the most basic setup possble, I'll try to make another one with your code:
http://plnkr.co/edit/sN9TagVBOdX3mkrxaTiu?p=preview
EDIT updated with the sample code. Everything seems to be working?
EDIT 2 the problem is OP wasn't running a webserver. Ng-Route needs a webserver to function properly.
My routing wasn't working because there was an exclamation point inserted in the url when I tried to navigate to my routes. I added $locationProvider like this
app.config(function($routeProvider, $locationProvider) {
$locationProvider.hashPrefix('');
to remove the exclamation point and my template views started appearing when I navigated to them. I found the answer here Exclamation mark after hash (#!) in angularjs app

Use ng-controller and $routeProvider at the same time

The issue is that I have an index page, whith a(some) partial(s) view(s) that we can call "A.html" with a controller "ACtrl" assigned by $routeProvider, but inside that partial view, I would like to use a different controller for some divs using ng-controller to include a "A1Ctrl".
Is this possible?
Not focus on any code, but in the concept if this is barely possible and how?
I tried to include in the partial view something like this with no success:
A.html
... //Other stuff for this partial view
<div ng-controller="A1Ctrl">
{{message}}
</div>
... //More stuff for this partial view
I have included the .js where the A1Ctrl is defined to the index page with same result. Any tip?
UPDATE:
I have create in plnkr a sample code to show what I want to do: http://plnkr.co/edit/hdpLMK3DbzNdz2KeHPEB?p=preview
I have partial view generated after clicking "Say hi" which has its own template ("first.html") and controller, injected by the $routeProvider. But in that partial view in first.html I want to add a which has its own controller for only that section of code. But I can't make it work, any suggestion?
I also tried to use Dependency Injection to include the module "multilinguage" into router.js with no success because it seems to generate an error.
index.html
<html ng-app="plunker">
<head>
... //Other imports
<script src="app.js"></script>
<script src="router.js"></script>
<script src="multilanguage.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
Say hi |
Say bye
<br/>
<div ng-view=""></div>
</body>
</html>
first.html
{{message}}
<div ng-controller="MultiLang">
{{message}}
</div>
router.js
var app = angular.module('router', ['ngRoute', 'multilanguage']).
config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when("/first", {
templateUrl: "first.html",
controller: "EngLang"
}).
when("/second", {
template: "Bye man!"
});
});
app.controller('EngLang', function($scope) {
$scope.message = 'Hi guys';
});
multilanguage.js
angular.module('multilanguage', []).
controller('MultiLang', function($scope){
$scope.message = "Hallo, Hola, Ciao, Ni Hao"
});
Thanks in advance.
Yes, also you can use nested controllers, for example:
<div ng-controller="A1Ctrl">
{{ message }}
<div ng-controller="subCtrl">
{{ message }}
</div>
</div>

AngularJS ng-template Directive Not Found in routeProvider

I am attempting to include multiple partial templates to be included in an ng-view, but the routeProvider directives are always trying to fetch the file from the server (not the embedded ng-template).
I have the following defined in my HTML:
<script type="text/ng-template" id="groupList.html">
<!-- contents -->
</script>
<script type="text/ng-template" id="participantList.html">
<!-- contents -->
</script>
<script src="js/app.js"></script> <!-- AngularJS app file -->
In my app.js file I have the following:
var myApp = angular.module('myApp', ['ngResource', '$strap.directives']);
// Update interpolateProvider for Django server
myApp.config(function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
});
myApp.config(function ($routeProvider)
{
$routeProvider.when('/', {
templateUrl: '../static/views/home.html'
});
$routeProvider.when('/group', {
controller: 'GroupCheckInCtrl',
templateUrl: 'groupList.html'
});
$routeProvider.when('/group/:groupId', {
controller: 'GroupCheckInCtrl',
templateUrl: 'participantList.html'
});
$routeProvider.otherwise({
redirectTo: '/'
});
});
When ever I load the page, I get an error in my browser console:
GET http://127.0.0.1:8000/visitorLog/group/groupList.html 404 (NOT FOUND)
The AngularJS app section of my page looks like this:
<div ng-app="myApp" ng-controller="GroupCheckInCtrl">
<!-- other content -->
<ng-view>Loading...</ng-view>
</div>
What am I missing that is not allowing AngularJS to load my ng-template script directive?
make sure that the inline script tags are children of the element that has the ng-app="myApp" attribute. If the script tags are outside this element, it will not work. The easiest way to fix this is to add the "ng-app='myApp'" to the tag. Here is an example of what I mean:
<body ng-app="plunker" ng-controller="MainCtrl">
<script type="text/ng-template" id="groupList.html">
Group list html
</script>
<script type="text/ng-template" id="participantList.html">
Participants list html
</script>
<ul>
<li>group</li>
<li>participant</li>
</ul>
<div ng-view>
Loading...
</div>
</body>
Here is the relevant plunker: http://plnkr.co/edit/K1gMiLenRk0oPkzlGNjv

Resources