Pass a value to another controller which executes first - javascript

I have two controllers headerController, aboutController.
headerController -> To maintain the navigation and redirection
aboutController -> works when about-us page loads.
My issue is I have to update the headerController variable value when aboutController loads. i.e When about us page loads, the navigation about-us should active, similar to all the pages.
This is my code:
app.service('shareService', function () {
var data;
return {
getProperty: function () {
return data;
},
setProperty: function (value) {
data = value;
}
};
});
app.controller('headerController', function ($scope, shareService) {
$scope.navigation = [
{url: '#!/home', name: 'Home'},
{url: '#!/about-us', name: 'About Us'},
{url: '#!/services', name: 'Services'}
];
var data = shareService.getProperty();
console.log(data);
$scope.selectedIndex = 0;
$scope.itemClicked = function ($index) {
console.log($index);
$scope.selectedIndex = $index;
};
});
app.controller('aboutController', function ($scope, shareService) {
console.log('test');
$scope.selectedIndex = 1;
shareService.setProperty({navigation: $scope.selectedIndex});
});
header.html:
<header ng-controller="headerController">
<div class="header">
<div class="first-half col-md-6">
<div class="row">
<div class="logo">
<img src="assets/img/logo.png" alt=""/>
</div>
</div>
</div>
<div class="second-half col-md-6">
<div class="row">
<div class="social-share">
<ul id="social-share-header">
<li><i class="fa fa-facebook" aria-hidden="true"></i></li>
<li><i class="fa fa-twitter" aria-hidden="true"></i></li>
<li><i class="fa fa-google-plus" aria-hidden="true"></i></li>
</ul>
</div>
</div>
</div>
<nav>
<ul ng-repeat="nav in navigation">
<li class="main-nav" ng-class="{ 'active': $index == selectedIndex }"
ng-click="itemClicked($index)">
{{nav.name}}
</li>
</ul>
</nav>
</div>
</header>
index.html
This is how my template works.
<body ng-app="myApp">
<section class="first-section">
<div ng-include="'views/header.html'"></div>
</section>
<section class="second-section">
<div ng-view></div>
</section>
<section class="last-section">
<div ng-include="'views/footer.html'"></div>
</section>
</body>
Update 1: Added index.html file.
Update 2: Issue explanation: If I run directly to the about us page, then still the home navigation is on active. But it should be About us

What is you are looking for is event based communication between your controllers. This can be easily done using. $rootScope.$on, $rootScope.$emit and $rootScope.$broadcast. Since explaining all three of them in this answer will be overkill. Kindly go through this article

Related

ng-click - Change tab on submitting form

I have a mean stack application where there is a left panel for navigation. One of the tabs have a form, and after I submit the form, I call a function, which after successful completion has a $state.go('secured.dashboard'); which redirects it to another tab(dashboard). This works fine, but on the left panel the previous tab(application form tab) is still highlighted as active. Although, On clicking the tab, the active menu is highlighted correctly.
So, the problem is when I click submit, it redirects to a different tab(dashboard) but on the left-navigation panel, some other tab(application Form) is highlightened, although I change the variable $scope.selectedMenu = "dashboard";. I have added the relevant code snippets from files:
header-template.html
<nav class="navbar-default navbar-side" role="navigation" style="width:200px">
<div class="sidebar-collapse">
<ul class="nav" id="main-menu">
<li>
<a id="page1" ng-class='{"active-menu": selectedMenu == "dashboard"}' ui-sref="secured.dashboard" ng-click='selectedMenu = "dashboard"'><i class="fa fa-dashboard "></i>Dashboard</a>
</li>
<li>
<a id="page2" ng-class='{"active-menu": selectedMenu == "applicationForm"}' ui-sref="secured.applicationForm" ng-click='selectedMenu = "applicationForm"'><i class="fa fa-handshake-o "></i>Application Forms</a>
</li>
<li>
<a id="page3" ng-class='{"active-menu": selectedMenu == "adminprofile"}' ui-sref="secured.adminprofile" ng-click='selectedMenu = "adminprofile"' ng-show="adminUserTrue"><i class="fa fa-user-secret"></i>Administrator</a>
</li>
<li>
<a id="page4" ng-class='{"active-menu": selectedMenu == "managerProfile"}' ui-sref="secured.managerProfile" ng-click='selectedMenu = "managerProfile"' ng-show="isManager"><i class="fa fa-user-secret"></i>Manager</a>
</li>
<li>
<a ng-class='{"active-menu": selectedMenu == "logout"}' href="" ng-click="logout()" ng-click='selectedMenu = "logout"'><i class="fa fa-sign-out fa-fw"></i> Logout</a>
</li>
</ul>
</div>
</nav>
dashboard.js
(function() {
var app = angular.module('dashboard', []);
app.config(['$stateProvider', function($stateProvider) {
$stateProvider.state('secured.dashboard', {
url: '/dashboard',
controller: 'DashboardController',
templateUrl: '/views/dashboard.html'
});
}]);
app.controller('DashboardController', ['$scope', 'AuthService', 'user', '$state', '$http', function($scope, AuthService, user, $state, $http) {
console.log("yes, the controller is here");
$scope.user = user;
AuthService.setUser(user);
$scope.applicationShow = {};
$scope.logout = function() {
AuthService.logout().then(function() {
$scope.user = null;
$state.go('unsecured');
})
}
applicationForm.js
(function() {
var app = angular.module('applicationForm', []);
app.config(['$stateProvider', function($stateProvider) {
$stateProvider.state('secured.applicationForm', {
url: '/applicationForm',
controller: 'applicationFormController',
templateUrl: '/views/applicationForm.html',
params: {
obj: null
}
});
}]);
app.controller('applicationFormController', ['$http', '$scope', '$state', '$uibModal', function($http, $scope, $state, $uibModal) {
console.log($state.params.obj);
if ($state.params.obj == null) {
$scope.application = {
technical: false,
business: false
};
} else {
$scope.application = $state.params.obj;
}
console.log("I am finally the application");
console.log($scope.application);
$scope.submitApplication = function() {
$scope.submitted = true;
console.log("Submit called");
console.log($scope.application.title);
console.log($scope.user.email);
console.log("Yes, i am here!");
console.log($scope.application.userEmail);
$scope.application.state = "SUBMITTED";
$scope.application.heirarchy = $scope.managerjson[$scope.application.managerName].senior;
console.log($scope.application.heirarchy);
var check = 0;
$http.get('/application/applicationlistNum/').then(function(response) {
$scope.application.number = response.data.value.sequence_value;
console.log($scope.application.number);
for (var i = 0, len = $scope.applicationList.length; i < len; i++) {
if ($scope.applicationList[i]._id == $scope.application._id) {
check = 1;
console.log("matched");
break;
}
}
if (check == 1) {
$http.put('/application/applicationlist/' + $scope.application._id, $scope.application).then(function(response) {
refresh();
});
} else {
$http.post('/application/applicationList', $scope.application).then(function(response) {
console.log("Successfully submitted");
refresh();
});
}
swal({
title: "Great!",
text: "We have received your request",
type: "success",
timer: 3000,
confirmButtonText: "Wohoo!"
});
var contactInfo = {
managerEmail: $scope.application.managerName,
selfEmail: $scope.application.userEmail,
name: $scope.managerjson[$scope.application.managerName].name
};
clear();
sendMail(contactInfo);
console.log("changing states");
$scope.selectedMenu = "dashboard";
$state.go('secured.dashboard');
});
};
applicationForm.html
<div class="col-lg-12">
<form class="well form-horizontal" id="contact_form" ng-submit="submitApplication()" name="form">
<fieldset>
<!-- some more fields -->
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-2">
<button type="submit" class="btn btn-primary"> Submit <span class="glyphicon glyphicon-send"></span></button>
<!-- <button class="btn btn-primary" ng-click="submitApplication()"> Submit <span class="glyphicon glyphicon-send"></span></button> -->
</div>
<div>
<button class="btn btn-warning" ng-click="saveApplication()"> Save <span class="glyphicon glyphicon-floppy-disk"></span></button>
</div>
</div>
</fieldset>
</form>
In applicationForm.js change $scope.selectedMenue = 'dashboard' to
$scope.selectedMenu = {name : "dashboard"};
And in your header template
<ul class="nav" id="main-menu">
<li>
<a id="page1" ng-class='{"active-menu": selectedMenu.name == "dashboard"}' ui-sref="secured.dashboard" ng-click='selectedMenu.name= "dashboard"'><i class="fa fa-dashboard "></i>Dashboard</a>
</li>
<li>
<a id="page2" ng-class='{"active-menu": selectedMenu.name== "applicationForm"}' ui-sref="secured.applicationForm" ng-click='selectedMenu.name= "applicationForm"'><i class="fa fa-handshake-o "></i>Application Forms</a>
</li>
<li>
<a id="page3" ng-class='{"active-menu": selectedMenu.name== "adminprofile"}' ui-sref="secured.adminprofile" ng-click='selectedMenu.name= "adminprofile"' ng-show="adminUserTrue"><i class="fa fa-user-secret"></i>Administrator</a>
</li>
<li>
<a id="page4" ng-class='{"active-menu": selectedMenu.name== "managerProfile"}' ui-sref="secured.managerProfile" ng-click='selectedMenu.name= "managerProfile"' ng-show="isManager"><i class="fa fa-user-secret"></i>Manager</a>
</li>
<li>
<a ng-class='{"active-menu": selectedMenu.name== "logout"}' href="" ng-click="logout()" ng-click='selectedMenu.name= "logout"'><i class="fa fa-sign-out fa-fw"></i> Logout</a>
</li>
</ul>

Angular: ngView and functions not working right away?

On my website, if you scroll down to the third section that says "Victorious Gaming" and hover over the arrows on the left and right, no text shows up. However, the second time and thereafter you hover over the arrows, the text correctly shows up. Why do they not work the very first time? The same applies to when you hover over the text "Victorious Gaming"
In my Controller, I have:
projectApp.controller("featuredController", ["$rootScope", "$scope", function ($rootScope, $scope) {
$scope.leftArrow = function(){
$(function(){
$(".left-arrow a").hover(function(){
$('.left-info').css('opacity','1');
}, function(){
$('.left-info').css('opacity','0');
});
});
};
$scope.rightArrow = function(){
$(function(){
$(".right-arrow a").hover(function(){
$('.right-info').css('opacity','1');
}, function(){
$('.right-info').css('opacity','0');
});
});
};
$scope.bigWords = function(){
$(function(){
$(".big-word-padding").hover(
function() {
$('.blur-background').fadeOut(700);
$('.big-word-padding').find('h2').css('color','blue');
$('.color-blue').css('color','white');
}, function() {
$('.blur-background').fadeIn(300);
$('.big-word-padding').find('h2').css('color','white');
$('.color-blue').css('color','blue');
});
$(".big-word-padding").hover(
function() {
$('.blur-background').fadeOut(700);
$('.big-word-padding').find('.m-title').css('color','white');
$('.big-word-padding').find('#manga-title').addClass('textShadowM');
$('.big-word-padding').find('.m-title').addClass('textShadowManga');
$('.color-blue').css('color','white');
}, function() {
$('.blur-background').fadeIn(300);
$('.big-word-padding').find('.m-title').css('color','rgb(26, 107, 156)');
$('.big-word-padding').find('#manga-title').removeClass('textShadowM');
$('.big-word-padding').find('.m-title').removeClass('textShadowManga');
$('.color-blue').css('color','blue');
});
});
};
}]);
My HTML:
<div class="ng-container" ng-controller="featuredController">
<div ng-view class="view-animate">
</div>
</div>
External HTML file(templates/featured-proj.html):
<div class="big-feature">
<div class="big-background second-background"></div>
<div class="blur-background second-background"></div>
<div class="big-word">
<div class="big-word-padding" ng-mouseover="bigWords()">
<h2> Victorious <span class="color-blue">Gaming</span></h2>
<h3>UI Developer. Design.</h3>
<hr>
<i class="fa fa-caret-right fa-3x" aria-hidden="true" id="arrow-project"></i>
</div>
</div>
<div class="left-arrow">
<i class="fa fa-angle-left" aria-hidden="true"></i>
</div>
<div class="left-info">
My Art
</div>
<div class="right-arrow">
<i class="fa fa-angle-right" aria-hidden="true"></i>
</div>
<div class="right-info">
Mangahere
</div>
<!-- <ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-shield"></i> Home</li>
<li><i class="fa fa-shield"></i> About</li>
<li><i class="fa fa-comment"></i> Contact</li>
</ul> -->
<div class="info-vic">
<div class="row-vic">
<div class="left-vic"></div>
<div class="right-vic"></div>
</div>
<div class="row-vic">
<div class="left-vic"></div>
<div class="right-vic"></div>
</div>
<div class="row-vic">
<div class="left-vic"></div>
<div class="right-vic"></div>
</div>
</div>
</div>
And my config for routing:
projectApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/feature', {
templateUrl : 'templates/featured-proj.html'
})
// route for the about page
.when('/feature2', {
templateUrl : 'templates/featured-proj-2.html'
})
// route for the contact page
.when('/feature3', {
templateUrl : 'templates/featured-proj-3.html'
})
.otherwise( { redirectTo: '/feature' } );
}]);
First, you have an extra $(function(){ ... }) wrapper both in leftArrow() and rightArrow().
In addition, the hover effect gets set only when when those functions are called for the first time. During that call, the opacity will not be modified.
I would replace ng-mouseover="leftArrow()" with ng-mouseenter="leftArrowShow()" ng-mouseleave="leftArrowHide()" and then define these functions like:
$scope.leftArrowShow = function() {
$('.left-info').addClass('show');
};
$scope.leftArrowHide = function() {
$('.left-info').removeClass('show');
};
And then, in CSS, have:
.left-info.show {
opacity: 1;
}
rightArrow() would be handled in a similar manner.

Compile error for Angular JS with js/ajax.js and index.html

When I compile my code there is an error with angular.
The code is written from a book, and it works when I load the page using the code at the end of the question.
There seems to be two issues from what I have read. Where do I put the $scope and $compile code?
Mostly, the question is how do I load a document ready trigger with a button for angular JS?
Or should I always load the angular js and hide the code?
<div id="myTabs">
<div class="menu">
<ul class= "tabs">
<li >LIST</li>
<li >GRID</li>
<li >GRID</li>
</ul>
</div>
<div class="container" style="margin-top:100px">
<div id="a">
</div>
<div id="b">
<ul class="gallery-items" id="grid">
</ul>
</div>
<div id="c" >
<div ng-controller="myController">
<div ng-repeat="item in items">
<img ng-src="{{item.img}}" />
{{item.description}}<br>
Rating: {{item.rating}} stars<br>
<span ng-repeat="idx in stars"
ng-class=
"{true: 'star', false: 'empty'}[idx <= item.rating]"
ng-click="adjustRating(item, idx)">
</span>
<hr>
</div>
</div>
</div>
</div>
ajax.js has a function that calls the #c tab to load
$(document).ready(function(){
$('#listC').click(function(){
angular.module('myApp', [])
.controller('myController', ['$scope', function($scope) {
$scope.stars = [1,2,3,4,5];
$scope.items = [100];
$.ajax({
type:'post',
url:'changeView.php',
data:{action: 'getGrid'},
success:function(data){
var data = JSON.parse(data);
for (i=0;i<data.length;i++) {
var imageLI = makeImage(data[i]['imageID'], data[i]['name'], data[i]['desc']);
$scope.items[i] = imageLI;
}
}
});
console.log($scope.items);
$scope.adjustRating = function(item, value){
item.rating = value;
};
}]);
});
$('#listC').trigger('click');
function makeImage(ID, name, description){
var image = {
description: description,
img: '../uploads/'+name,
rating: 4
}
return image;

Angular Directive Bug With View

I was doing a very quick exercise with angular directives. My code is very simple.
app.js:
var app = angular.module('readingList', []);
app.controller('BooksController', function($scope){
$scope.books = books;
$scope.genres = genres;
})
app.directive('bookGenres', function(){
return {
restrict: 'E',
templateURL: 'partials/book-genres.html'
};
});
var books = [{
title: 'ABCD',
author: 'E. Fgh',
isbn: '123414312341234',
review: 'Hello world',
rating: 4,
genres: {
'non-fiction': true, fantasy: false
}
}];
var genres = ["foo1","bar2","foo2","bar3"];
}
app.html:
<div class="row" ng-controller="BooksController">
<button class="btn btn-default">Create Review</button>
<hr />
<hr />
<ul class="list-unstyled col-sm-8" >
<li class="book row" ng-repeat="book in books">
<aside class="col-sm-3">
<a href="http://www.amazon.com/gp/product/{{book.isbn}}">
<img ng-src="http://images.amazon.com/images/P/{{book.isbn}}.01.ZTZZZZZZ.jpg" alt="" class="full"/>
</a>
<p class="goodRating rating">{{book.rating}}/5</p>
</aside>
<div class="col-sm-9 col-md-8">
<h3>
<a href="https://rads.stackoverflow.com/amzn/click/com/0553593714" rel="nofollow noreferrer">
{{book.title}}
</a>
</h3>
<cite class="text-muted">{{book.author}}</cite>
<p>{{book.review}}</p>
<!-- Put Genre Here -->
<book-genres></book-genres>
<ul class="list-unstyled">
<li ng-repeat="(genre, state) in book.genres">
<span class="label label-primary" ng-show="state === true">
{{genre}}
</span>
</li>
</ul>
</div>
</li>
</ul>
</div>
book-genres.html:
<ul class="list-unstyled">
<li ng-repeat="(genre, state) in book.genres">
<span class="label label-primary" ng-show="state === true">
{{genre}}
</span>
</li>
</ul>
Everything renders with the view except my book-genres directive. For reason, it doesn't work. I have checked the documentation. I checked other similar examples and nothing. If I can't get this directive to work, rendering out the other components such as the image is going to be a problem. I also checked the path of the partials views as well.
There's a couple possibilities here. You need to be sure to inject $scope into your controller:
app.controller('BooksController', ['$scope', function($scope) {
// do stuff
}]);
book.genres is not defined anywhere, so your ng-repeat has no items to display.
templateURL is also incorrect, it should be templateUrl.

angularjs ng-include pass value from controller

I'm trying to include subpages to my main page..
I'm using ng-include.. when I tried to put using this ng-include="'samplePage.php'" it works... but what I want is to assign the value of ng-include in the controller...
here's my hmtl code
<div id="navbar-override" class = "navbar navbar-inverse navbar-static-top" ng-controller="indexCtrl">
<div class = "container">
<div class = "navbar-header">
<a href = "index.html" class = "navbar-brand">
Sample App
</a>
<button id="navbar-btn-override" class = "navbar-toggle" data-toggle = "collapse" data-target = ".navHeaderCollapse">
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
</div>
<div class = "collapse navbar-collapse navHeaderCollapse">
<ul class = "nav navbar-nav navbar-right">
<li ng-repeat="link in Links" ng-class="{'active': selectedItem === link}">
{{ link }}
</li>
</ul>
</div>
</div>
</div>
<div class="container" ng-include="pages">
<!--subpages will append here-->
</div>
my controller.js
indexApp.controller('indexCtrl', ['$window','$scope', '$http', function($window, $scope, $http) {
$scope.pages = "./pages/customer.php";
}]);
if you ask me why I do this.. because I'm planing to use ng-include dynamically......
I'm still new to angularjs so bear with me...
thanks in advance..
This will work,
Your HTML :
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div ng-include src="template.url" onload='myFunction()'></div>
</div>
<!-- template1.php-->
<script type="text/ng-template" id="./pages/template1.php">
Content of template1.php
</script>
<!-- template2.php-->
<script type="text/ng-template" id="./pages/template2.php">
<p ng-class="color">Content of template2.php</p>
</script>
Controller :
function Ctrl($scope) {
$scope.templates = [{
name: 'template1.php',
url: './pages/template1.php'},
{
name: 'template2.php',
url: './pages/template2.php'}];
$scope.template = $scope.templates[0];
$scope.myFunction = function() {
$scope.color = 'red';
}
}
http://jsfiddle.net/MfHa6/1517/

Categories