image slider doesn't work using route in angular js - javascript

I'm newbie to Angular js..But try to make an image slider in my file..
And also I'm using route..Acutally I'm having three pages..
1.home
2.about
3.contact
For this I create an index file in which I add header and footer
While I'm adding the slider in my index page it works fine for me..
But if I did the same thing in my home page..It won't work and I din't find any errors in my console also..
I don't know how to fix it..
Here I attach my all codes..
script.js
// create the module and name it scotchApp
var scotchApp = angular.module('scotchApp', ['ngRoute','ngAnimate', 'ngTouch']);
// configure our routes
scotchApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'homeController'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
});
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
//Logo
$scope.logo = 'logo.png';
//username
$scope.username = 'Jonathan Stephanopalus';
//footercontent
$scope.footer = [
{ title: 'Contacts' },
{ title: 'Feedback' },
{ title: 'Help' },
{ title: 'Site Map' },
{ title: 'Terms & Conditions' },
{ title: 'Privacy Statement' },
{ title: 'Cookie Policy' },
{ title: 'Trademarks' }
];
});
scotchApp.controller('homeController', function($scope) {
// create a message to display in our view
$scope.message = "Lorem Ipsum ";
//lastdiv
$scope.lastdiv = { image : "women_wright.png" ,title:"Get to know Cisco better: Community Forums"};
//slider
$scope.slides = [
{image: 'images/img00.jpg', description: 'Image 00'},
{image: 'images/img01.jpg', description: 'Image 01'},
{image: 'images/img02.jpg', description: 'Image 02'},
{image: 'images/img03.jpg', description: 'Image 03'},
{image: 'images/img04.jpg', description: 'Image 04'}
];
$scope.direction = 'left';
$scope.currentIndex = 0;
$scope.setCurrentSlideIndex = function (index) {
$scope.direction = (index > $scope.currentIndex) ? 'left' : 'right';
$scope.currentIndex = index;
};
$scope.isCurrentSlideIndex = function (index) {
return $scope.currentIndex === index;
};
$scope.prevSlide = function () {
$scope.direction = 'left';
$scope.currentIndex = ($scope.currentIndex < $scope.slides.length - 1) ? ++$scope.currentIndex : 0;
};
$scope.nextSlide = function () {
$scope.direction = 'right';
$scope.currentIndex = ($scope.currentIndex > 0) ? --$scope.currentIndex : $scope.slides.length - 1;
};
});
scotchApp.animation('.slide-animation', function () {
return {
beforeAddClass: function (element, className, done) {
var scope = element.scope();
if (className == 'ng-hide') {
var finishPoint = element.parent().width();
if(scope.direction !== 'right') {
finishPoint = -finishPoint;
}
TweenMax.to(element, 0.5, {left: finishPoint, onComplete: done });
}
else {
done();
}
},
removeClass: function (element, className, done) {
var scope = element.scope();
if (className == 'ng-hide') {
element.removeClass('ng-hide');
var startPoint = element.parent().width();
if(scope.direction === 'right') {
startPoint = -startPoint;
}
TweenMax.fromTo(element, 0.5, { left: startPoint }, {left: 0, onComplete: done });
}
else {
done();
}
}
};
});
scotchApp.controller('aboutController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
scotchApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
home.html
<div ng-controller="homeController">
<div class="container slider">
<img ng-repeat="slide in slides" class="slide slide-animation nonDraggableImage" ng-swipe-right="nextSlide()" ng-swipe-left="prevSlide()" ng-hide="!isCurrentSlideIndex($index)" ng-src="{{slide.image}}">
<a class="arrow prev" href="#" ng-click="nextSlide()"></a>
<a class="arrow next" href="#" ng-click="prevSlide()"></a>
<nav class="nav">
<div class="wrapper">
<ul class="dots">
<li class="dot" ng-repeat="slide in slides">
{{slide.description}}
</li>
</ul>
</div>
</nav>
test
</div>
</div>
index.html
<!DOCTYPE html>
<!-- define angular app -->
<html ng-app="scotchApp">
<head>
<!-- SCROLLS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<!-- <link rel="stylesheet" href="styles/main.css" /> -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />
<!-- <link href="css/bootstrap.css" rel="stylesheet"> -->
<link rel="stylesheet" href="css/styles.css">
<!-- <script src="js/app.js"></script> -->
<!-- SPELLS -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular-touch.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.10.3/TweenMax.min.js"></script>
<!-- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script> -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script src="script.js"></script>
</head>
<!-- define angular controller -->
<body class="angular_class" ng-controller="mainController">
<nav class="navbar navbar-default">
<div class="container">
<div class="menu_1">
<div class="navbar-header">
<a class="navbar-brand" href="/"><img src="image/{{logo}}"></a>
</div>
<div class="f_right">
<p>Welcome, {{ username }}</p>
<img src="image/sml_logo.png">
</div>
</div>
<div class="menu_1">
<ul class="nav navbar-nav navbar-left">
<li ng-repeat="teams in teamArray">{{ teams.team_name }}</li>
</ul>
<div class="f_right">
<input type="text" class="searchbox" placeholder="Search"></input>
</div>
</div>
</div>
</nav>
<div id="main">
<!-- angular templating -->
<!-- this is where content will be injected -->
<div ng-view></div>
</div>
<footer class="text-center">
<div class="footer_block">
<span ng-repeat="ft in footer">{{ ft.title }}</span>
</div>
</footer>
</body>
</html>
And for information I follow this link
Could someone please help me out of this..
Thank you,

Change home.html
<div ng-controller="homeController">
<div class="container slider">
<img ng-repeat="slide in slides" class="slide slide-animation nonDraggableImage" ng-swipe-right="nextSlide()" ng-swipe-left="prevSlide()" ng-hide="!isCurrentSlideIndex($index)" ng-src="{{slide.image}}">
<a class="arrow prev" href="#" ng-click="nextSlide()"></a>
<a class="arrow next" href="#" ng-click="prevSlide()"></a>
<nav class="nav">
<div class="wrapper">
<ul class="dots">
<li class="dot" ng-repeat="slide in slides">
{{slide.description}}
</li>
</ul>
</div>
</nav>
test
</div>
with
<div class="container slider">
<img ng-repeat="slide in slides" class="slide slide-animation nonDraggableImage" ng-swipe-right="nextSlide()" ng-swipe-left="prevSlide()" ng-hide="!isCurrentSlideIndex($index)" ng-src="{{slide.image}}">
<a class="arrow prev" href="#" ng-click="nextSlide()"></a>
<a class="arrow next" href="#" ng-click="prevSlide()"></a>
<nav class="nav">
<div class="wrapper">
<ul class="dots">
<li class="dot" ng-repeat="slide in slides">
{{slide.description}}
</li>
</ul>
</div>
</nav>
test
</div>

Related

Bootstrap navbar using angular routes glitches to left side on specific active tabs

Sorry if it is a dumb question, I am a beginner to web design and couldn't find an answer, even after a lot of googling / searching on here.
So as you can read in the title, my issue is, that upon clicking on "EX5" or "EX6" in my navbar, it glitches to the left side of the screen, instead of staying at the top.
Below is my code, since EX5 and EX6 are basically the same thing, I'll post the shorter one in here:
Navbar:
<!DOCTYPE html>
<html ng-app='sampleApp'>
<head>
<link data-require="bootstrap-css" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular-route.js" data-semver="1.4.9"></script>
<script src="../js/script.js"></script>
<script src="../js/headerController.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-default" ng-controller="HeaderController">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">JS</a>
</div>
<ul class="nav navbar-nav">
<li ng-class="{ active: isActive('/')}">EX1</li>
<li ng-class="{ active: isActive('/ex2')}">EX2</li>
<li ng-class="{ active: isActive('/ex3')}">EX3</li>
<li ng-class="{ active: isActive('/ex4')}">EX4</li>
<li ng-class="{ active: isActive('/ex5')}">EX5</li>
<li ng-class="{ active: isActive('/ex6')}">EX6</li>
<li ng-class="{ active: isActive('/ex7')}">EX7</li>
<li ng-class="{ active: isActive('/ex8')}">EX8</li>
<li ng-class="{ active: isActive('/ex9')}">EX9</li>
<li ng-class="{ active: isActive('/ex10')}">EX10</li>
</ul>
</div>
</nav>
</header>
<ng-view></ng-view>
</body>
</html>
EX6:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../styles/stylesheet.css">
<title>Exercise 6</title>
<script src="../js/script.js"></script>
</head>
<body>
<div>
<h2>Add an image, upon clicking, change the image</h2>
<hr>
<img onclick="changeImg()" id="sourceImg" src="../styles/images/diluc.jpg" alt="diluc">
</div>
</body>
</html>
script:
//change img
var currentImage = "../styles/images/diluc.jpg"
function changeImg(){
if(currentImage == "../styles/images/diluc.jpg"){
document.getElementById("sourceImg").src="../styles/images/venti.jpg";
currentImage = "../styles/images/venti.jpg"
}else{
document.getElementById("sourceImg").src = "../styles/images/diluc.jpg"
currentImage = "../styles/images/diluc.jpg"
}
}
/////Nav
(function () {
var app = angular.module('sampleApp',['ngRoute']);
app.config(function ($routeProvider){
$routeProvider
.when('/',{
templateUrl:'../exercises/ex1.html'
})
.when('/ex2',{
templateUrl:'../exercises/ex2.html'
})
.when('/ex3',{
templateUrl:'../exercises/ex3.html'
})
.when('/ex4',{
templateUrl:'../exercises/ex4.html'
})
.when('/ex5',{
templateUrl:'../exercises/ex5.html'
})
.when('/ex6',{
templateUrl:'../exercises/ex6.html'
})
.when('/ex7',{
templateUrl:'../exercises/ex7.html'
})
.when('/ex8',{
templateUrl:'../exercises/ex8.html'
})
.when('/ex9',{
templateUrl:'../exercises/ex9.html'
})
.when('/ex10',{
templateUrl:'../exercises/ex10.html'
})
.otherwise({ redirectTo:'/'});
});
})();
My header controller:
(function () {
var headerController = function ($scope, $location)
{
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
};
angular.module('sampleApp').controller('HeaderController',headerController);
}());
And lastly my 3 lines of css:
#sourceImg{
width: 500px;
}
I would greatly appreciate your help, as I am unable to solve this myself. Thank you
Solved, issue was with my css file, there was some gibberish in there oof

Angular runs the controller multiple times

I am currently developing a chat web app. This should be realized as a single page app. For this I use Angular Router. I use socket-io to send the messages from the client to the server. Navigating between the routes actually works quite well.
In the route home.html, there is an input element for entering the message. After clicking the button, it will be added as an <li> element in the <ul> list and displayed. When starting the app, I can write messages normally. But if I navigate from the home route to another route and then go back to home and enter the message, it will be sent twice. The next time you navigate back and forth then three times, and so on. As if the controller is running several times.
I cannot find a solution to this problem on the internet. But that has to go anyway.
P.S: I have only included a script file in index.html, because I use gulp to put all the js files together in one file.
Here is the code.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">
<title>FB4 Messenger</title>
<meta name="viewport" content="width=device-width, user-scalable=xo, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="css/style.css">
</head>
<body ng-app="chatApp">
<div class="loader">
<div class="loader-text">Laden...</div>
<div class="progress">
<div class="progress-bar progress-bar-danger progress-bar-striped active" role="progressbar" style="width: 100%"></div>
</div>
<!--progress-->
</div>
<!--loader-->
<header>
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data- toggle="collapse" data-target="#collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<section class="layout">
<div class="branding">
<a href="/">
<img src="images/header/app_fh_logo.png" alt="App logo">
</a>
</div>
<!--branding-->
</section>
<!--layout-->
</div>
<!--navbar-header-->
</div>
<div class="collapse navbar-collapse" id="collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active">
<a href="/">
<span class="glyphicon glyphicon-home"></span>
Startseite
</a>
</li>
<li>
<a href="/profile">
<span class="glyphicon glyphicon-user"></span>
Konto
</a>
</li>
<li>
<a href="/about">
<span class="glyphicon glyphicon-info-sign"></span>
Über
</a>
</li>
</ul>
</div>
<!-- navbar collapse -->
</nav>
</header>
<!--header-->
<!-- ANGULAR DYNAMIC CONTENT -->
<div ng-view></div>
<script src="js/script.js"></script>
</body>
</html>
home.html
<div class="container">
<ul id="messages"></ul>
<div>
<input id="m" ng-model="message" autocomplete="off" />
<button id="send" ng-click="send()">Send</button>
</div>
</div>
about.html
<div class="container">
<div class="card">
<img class="card-img-top" src="../images/header/app_fh_logo.png" alt="Card image cap">
<div class="card-body">
<h3 class="card-title">FB4 Messenger</h3>
<p class="card-text">Version: 0.0.1 </br> Ⓒ </p>
Startseite
</div>
</div>
</div>
app.js
let $ = jQuery = require("jquery");
require("./bootstrap.min");
require("angular");
require("angular-route");
angular.module("chatApp", ["ngRoute", "appRoutes", "MainCtrl", "ProfileCtrl", "AboutCtrl"]);
$(function() {
$(".loader").fadeOut(1000);
});
appRoutes.js
angular.module("appRoutes", []).config(["$routeProvider", "$locationProvider",
function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "views/home.html",
controller: "MainController"
})
.when("/profile", {
templateUrl: "views/profile.html",
//controller: "ProfileController"
})
.when("/about", {
templateUrl: "views/about.html",
//controller: "AboutController"
});
$locationProvider.html5Mode(true);
}
]);
mainCtrl.js (here the message is sent to the server)
angular.module("MainCtrl", []).controller("MainController", ["$scope",
function ($scope) {
let io = require("socket.io-client");
let socket = io.connect();
$scope.send = function () {
socket.emit("message", $scope.message);
$scope.message = "";
};
$("body").keypress(function (event) {
if (event.keyCode === 13) {
$("#send").click();
}
});
socket.on("message", function (m) {
let $li = $("<li>").text(m);
$("#messages").append($li);
});
}
]);
And the Server, index.js that receives the messages
const express = require("express");
const http = require("http");
let app = express();
let server = http.createServer(app);
app.use(express.static(__dirname + "/"));
app.get("*", function (req, res){
res.sendFile(__dirname+"/index.html");
});
let io= require("socket.io")(server);
io.on("connection", function (socket) {
socket.on("message", function (m) {
io.emit("message", m);
console.log(m);
});
});
server.listen(3000, function () {
console.log("Server runing");
});
This is problem.
$("body").keypress(function (event) {
if (event.keyCode === 13) {
$("#send").click();
}
});
Everytime your controller loads this is attached to the body as a new function. So it triggers everytime the same function call.
I suggest you could use this
$("body").removeAttr("keypress");
$("body").keypress(function (event) {
if (event.keyCode === 13) {
$("#send").click();
}
});
Better yet, use ng-click/ng-keyup and provide a function in scope
// home.html
ng-keyup="$event.keyCode == 13 && vm.sendFn()"
// in controller
vm.sendFn=function(){
... code ...for ..send
}
Edited
Can you change MainController this way and try.
It probably happens because of something similar to this -
https://github.com/angular-fullstack/generator-angular-fullstack/issues/490
let io = require("socket.io-client");
let socket = io.connect();
socket.on("message", function (m) {
let $li = $("<li>").text(m);
$("#messages").append($li);
});
angular.module("MainCtrl", []).controller("MainController", ["$scope",
function ($scope) {
$scope.send = function () {
socket.emit("message", $scope.message);
$scope.message = "";
};
}
]);

Bind events not working

With the code below, why does $("#sidenav-overlay").trigger("click") work while this.$sideNavOverlay.trigger("click") doesn't work?
(function($) {
$(function() {
var app = {
init: function() {
this.cacheDom();
this.bindEvents();
},
cacheDom: function() {
this.$buttonCollapse = $('.button-collapse');
this.$sideNavClear = $("#side-nav-clear");
this.$sideNavOverlay = $("#sidenav-overlay");
},
bindEvents: function() {
this.$buttonCollapse.sideNav();
this.$sideNavClear.on('click', this.closeSideNavigation.bind(this));
},
closeSideNavigation: function() {
console.log('closesideNavigation');
console.log(this);
console.log(this.$sideNavOverlay);
console.log($("#sidenav-overlay"));
//$("#sidenav-overlay").trigger("click");
this.$sideNavOverlay.trigger("click");
}
};
app.init();
}); // end of document ready
})(jQuery); // end of jQuery name space
.icon-block {
padding: 0 15px;
}
.icon-block .material-icons {
font-size: inherit;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="http://materializecss.com/css/ghpages-materialize.css" type="text/css" rel="stylesheet" media="screen,projection" />
<nav class="light-blue lighten-1" role="navigation">
<div class="nav-wrapper container"><a id="logo-container" href="#" class="brand-logo">Logo</a>
<ul class="right hide-on-med-and-down">
<li>Navbar Link
</li>
</ul>
<ul id="nav-mobile" class="side-nav">
<li>Navbar Link <a class="right" id="side-nav-clear" style="margin-top: 22px;"><i class="material-icons small icon-demo">clear</i></a>
</li>
</ul>
<i class="material-icons">menu</i>
</div>
</nav>
<div class="section no-pad-bot" id="index-banner">
<div class="container">
<h1 class="header center orange-text">Starter Template</h1>
</div>
</div>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://materializecss.com/bin/materialize.js"></script>
The only thing I can think of that would account for the reported symptom is that something in code you haven't shown is removing the old #sidenav-overlay (the one you cached in your property) and then appending a new #sidenav-overlay instead. So you're triggering the event on the old, no-longer-in-the-page element instead of the new one.
And in fact, that's what's happening, and we can see by checking to see if the #sidenav-overlay you've saved is the same element that's in the DOM later when clicked (it isn't):
(function($) {
$(function() {
var app = {
init: function() {
this.cacheDom();
this.bindEvents();
},
cacheDom: function() {
this.$buttonCollapse = $('.button-collapse');
this.$sideNavClear = $("#side-nav-clear");
this.$sideNavOverlay = $("#sidenav-overlay");
},
bindEvents: function() {
this.$buttonCollapse.sideNav();
this.$sideNavClear.on('click', this.closeSideNavigation.bind(this));
},
closeSideNavigation: function() {
console.log(
"Same element? " +
($("#sidenav-overlay")[0] === this.$sideNavOverlay[0])
);
$("#sidenav-overlay").trigger("click");
}
};
app.init();
}); // end of document ready
})(jQuery); // end of jQuery name space
.icon-block {
padding: 0 15px;
}
.icon-block .material-icons {
font-size: inherit;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="http://materializecss.com/css/ghpages-materialize.css" type="text/css" rel="stylesheet" media="screen,projection" />
<nav class="light-blue lighten-1" role="navigation">
<div class="nav-wrapper container"><a id="logo-container" href="#" class="brand-logo">Logo</a>
<ul class="right hide-on-med-and-down">
<li>Navbar Link
</li>
</ul>
<ul id="nav-mobile" class="side-nav">
<li>Navbar Link <a class="right" id="side-nav-clear" style="margin-top: 22px;"><i class="material-icons small icon-demo">clear</i></a>
</li>
</ul>
<i class="material-icons">menu</i>
</div>
</nav>
<div class="section no-pad-bot" id="index-banner">
<div class="container">
<h1 class="header center orange-text">Starter Template</h1>
</div>
</div>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://materializecss.com/bin/materialize.js"></script>
So unless you can prevent whatever's removing and replacing the element from doing so, just look it up when you need it. (In general, unless you have a good reason for doing something else, looking up elements when you need them is preferable to keeping them in properties or variables.)

AngularJS $routeprovider Routing in Mutitab

I was using this example to build the login page
angular-authentication-example
Once login to this app the home screen should have multi-tab view as mentioned in the below example
plunker
<ul class="nav nav-tabs" ng-controller="TabsCtrl">
<li ng-class="tabClass(tab)" ng-repeat="tab in tabs" tab="tab">{{tab.label}}</li>
</ul>
The issue I am facing is the multi-tab is not embedded as Single page App. As mentioned in the demo it should embed in the same view but once I integrated, it is showing as different view. For example, when I click jobs it is taking to new html page but not included in the same view as in the plunker demo .I want to use the angularjs route provider instead of state provider and the reason is login authentication example is best and I don't want to change the entire logic.
Update
Version 1 (Without routing) Plunker Demo
It will redirect to a new view if you use #/jobs syntax. Here is a complete working solution without routes:
Your code on plunker is working because you didn't include ngRoute in your code.
View in plunker demo
app.js
$scope.tabs = [
{ id : 'jobs', label : 'Jobs', templateUrl:'jobs-partial.html' },
{ id : 'invoices', label : 'Invoices',templateUrl: 'invoices-partial.html' },
{ id : 'payments', label : 'Payments',templateUrl: 'payments-partial.html' }
];
$scope.activeTab = $scope.tabs[0];
$scope.changeActiveTab = function (tab) {
$scope.activeTab = tab;
};
$scope.isActiveTab = function (tabId) {
return tabId === $scope.activeTab;
}
Inside index.html
<body ng-controller="TabsCtrl">
<ul class="nav nav-tabs" >
<li ng-class="{active: isActiveTab(tab.id)}" ng-repeat="tab in tabs">
{{tab.label}}
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" ng-class="{'in active': isActiveTab(tab.id)}" ng-repeat="tab in tabs"
ng-include="tab.templateUrl">
</div>
</div>
</body>
Version 2 (With routing) Plunker Demo
index.html
<!DOCTYPE html>
<html ng-app="plunkerApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script src="https://code.angularjs.org/1.4.8/angular-route.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
app.js
angular
.module('untitled4App', [
'ngRoute'
])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/jobs', {
templateUrl: '/views/jobs-partial.html',
controller: 'JobsCtrl'
}).when('/invoices', {
templateUrl: '/views/invoices-partial.html',
controller: 'InvoicesCtrl'
}).when('/payments', {
templateUrl: '/views/payments-partial.html',
controller: 'PaymentsCtrl'
});
// make this demo work in plunker
$locationProvider.html5Mode(false);
}])
.factory('tabsService', function () {
return {
tabs: function () {
return [
{id: 'jobs', label: 'Jobs'},
{id: 'invoices', label: 'Invoices'},
{id: 'payments', label: 'Payments'}
]
},
activeTab: '',
isActiveTab: function (tabId) {
return tabId === this.activeTab;
}
}
})
.controller('JobsCtrl', ['$scope', 'tabsService', function ($scope, tabsService) {
$scope.tabs = tabsService.tabs();
$scope.tabsService = tabsService;
tabsService.activeTab = $scope.tabs[0].id;
}])
.controller('InvoicesCtrl', ['$scope', 'tabsService', function ($scope, tabsService) {
$scope.tabs = tabsService.tabs();
$scope.tabsService = tabsService;
tabsService.activeTab = $scope.tabs[1].id;
}])
.controller('PaymentsCtrl', ['$scope', 'tabsService', function ($scope, tabsService) {
$scope.tabs = tabsService.tabs();
$scope.tabsService = tabsService;
tabsService.activeTab = $scope.tabs[2].id;
}]);
jobs.partial.html
<ul class="nav nav-tabs">
<li ng-class="{active: tabsService.isActiveTab(tab.id)}" ng-repeat="tab in tabs">
{{tab.label}}
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active">
Jobs
</div>
</div>
invoices-partial.html
<ul class="nav nav-tabs">
<li ng-class="{active: tabsService.isActiveTab(tab.id)}" ng-repeat="tab in tabs">
{{tab.label}}
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active">
Invoices
</div>
</div>
payments-partial.html
<ul class="nav nav-tabs">
<li ng-class="{active: tabsService.isActiveTab(tab.id)}" ng-repeat="tab in tabs">
{{tab.label}}
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active">
Payments
</div>
</div>

AngularJS Undefined Variables When Trying To Update View From Controller

I am new to AngularJS and am trying to rewrite my webpage in the "angular way" instead of using jquery but I am running into some problems with my understanding.
I have my HTML like so:
<body style="padding-top: 0px;" data-spy="scroll" ng-app="SummerMill">
<section id="intro" class="main style1 dark">
<!-- Header -->
<header ng-controller="MainController" id="header">
<!-- Logo -->
<h1 id="logo">Summer Mill</h1>
<a ng-mouseover="locations()"
style="color:black;text-decoration:initial;"
id="logoii"
href="http://localhost/locations">Locations</a>
<!-- Nav -->
<nav id="nav">
<ul class="nav navbar-nav">
<li ng-repeat="headerLink in headerLinks"><a ng-init="content=headerLink.text" href="#{{content}}">{{content}}</a></li>
</ul>
</nav>
</header>
Then my controller:
app.controller('MainController', ['$scope', function($scope) {
$scope.headerLinks = [
{
text: 'Intro',
alternativeText: 'Arlington'
},
{
text: 'Wholesale',
alternativeText: 'New York'
}
];
$scope.locations = function() {
content = headerLinks.alternativeText;
}
}]);
So basically, on hover, I want the <li> content to change. I know the hover event is being fired, and correctly so. The error I get is that ReferenceError: headerLinks is not defined which is odd to me because it is in the controller itself, so I tried content = $scope.headerLinks.alternativeText; and that stopped the error but I guess content in the controller is not the same as content in ng-init.
What is the right way to do this? Perhaps I am thinking of this the wrong way.
For your case better a bit simplify your code like, for example use ng-if and flag isOver
angular.module('app',[])
.controller('MainController',function($scope){
$scope.headerLinks = [
{
text: 'Intro',
alternativeText: 'Arlington'
},
{
text: 'Wholesale',
alternativeText: 'New York'
}
];
$scope.locations = function() {
content = headerLinks.alternativeText;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!-- Header -->
<header ng-app="app" ng-controller="MainController" id="header">
<!-- Logo -->
<h1 id="logo">Summer Mill</h1>
<a ng-mouseover="isOver=true" ng-mouseout="isOver=false"
style="color:black;text-decoration:initial;"
id="logoii"
href="http://localhost/locations">Locations</a>
<!-- Nav -->
<nav id="nav">
<ul class="nav navbar-nav">
<li ng-repeat="headerLink in headerLinks">
<a ng-if="!isOver" href="#{{headerLink.text}}">{{headerLink.text}}</a>
<a ng-if="isOver" href="#{{headerLink.alternativeText}}">{{headerLink.alternativeText}}</a>
</li>
</ul>
</nav>
</header>
also you can you ternary operator instead ng-if like this
angular.module('app',[])
.controller('MainController',function($scope){
$scope.headerLinks = [
{
text: 'Intro',
alternativeText: 'Arlington'
},
{
text: 'Wholesale',
alternativeText: 'New York'
}
];
$scope.locations = function() {
content = headerLinks.alternativeText;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!-- Header -->
<header ng-app="app" ng-controller="MainController" id="header">
<!-- Logo -->
<h1 id="logo">Summer Mill</h1>
<a ng-mouseover="isOver=true" ng-mouseout="isOver=false"
style="color:black;text-decoration:initial;"
id="logoii"
href="http://localhost/locations">Locations</a>
<!-- Nav -->
<nav id="nav">
<ul class="nav navbar-nav">
<li ng-repeat="headerLink in headerLinks">
{{!isOver ? headerLink.text : headerLink.alternativeText}}
</li>
</ul>
</nav>
</header>
or even without condition like
angular.module('app', [])
.controller('MainController', function($scope) {
$scope.currentText = 'text';
$scope.headerLinks = [{
text: 'Intro',
alternativeText: 'Arlington'
}, {
text: 'Wholesale',
alternativeText: 'New York'
}];
$scope.locations = function() {
content = headerLinks.alternativeText;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!-- Header -->
<header ng-app="app" ng-controller="MainController" id="header">
<!-- Logo -->
<h1 id="logo">Summer Mill</h1>
<a ng-mouseover="currentText='alternativeText'" ng-mouseout="currentText='text'" style="color:black;text-decoration:initial;" id="logoii" href="http://localhost/locations">Locations</a>
<!-- Nav -->
<nav id="nav">
<ul class="nav navbar-nav">
<li ng-repeat="headerLink in headerLinks">
{{headerLink[currentText]}}
</li>
</ul>
</nav>
</header>

Categories

Resources