Angularjs nested controller called just one time - javascript

I'm new in Angularjs and I have an app, with some "projects", which have a local menu displayed on some pages. Index.html contains the main navbar with footer :
<body ng-app="ysi-app" ng-controller="MainController">
<div class="page-content">
<div class="row">
<div class="col-md-2">
<div class="sidebar content-box" style="display: block;">
<ul class="nav">
<!-- Main menu -->
<li ng-if="isAuthenticated()">{{name}}</li>
<li class="current">Dashboard</li>
<li>Projects</li>
</ul>
</div>
<div ng-if="isAuthenticated() && displayProjectMenu == true" ng-include="'views/localMenu.html'" ng-controller="LocalMenuController">
</div>
</div>
<div ng-view></div>
</div>
So I have a nested controller LocalMenuController for the local menu and a main controller. The project controller sets the datas :
angular.module('ProjectCtrl',[]).controller('ProjectController',function($scope,$location, ProjectService,$route, AuthenticationService, $rootScope){
$scope.setProjectDatas = function(projectName, projectId){
ProjectService.setName(projectName);
$rootScope.projectId = projectId;
};});
I set the id of one project to the $rootScope for testing (I have a Service which will do that better) and get it in the LocalMenuController :
angular.module('LocalMenuCtrl',[]).controller('LocalMenuController', function($scope, ProjectService, $rootScope) {
$scope.projectId = '';
$scope.projectId = $rootScope.projectId;
});
I display projects in a table and when I clicked on one of it, the function setProjectDatas(name,id) is called. The problem is when I clicked on one project, the id of the project is correct and set but when I go previous and clicked on another project, the id is the old id of the project previously clicked. The datas are not updating. I googled my problem but found nothing on it.
I think the LocalMenuController is called only one time but not after.
What am I doing wrong ?
Thank you
UPDATE
I've created a Directive which displays the template but it's still not updating the partial view localMenu.
LocalMenu Directive :
angular.module('LocalMenuCtrl',[]).controller('LocalMenuController', function($scope, ProjectService, $rootScope) {
console.log('-> LocalMenu controller');
})
.directive('localMenu', function($rootScope){
return {
templateUrl: '/YSI-Dev/public/views/partials/localMenu.html',
link: function(scope){
scope.projectId = $rootScope.projectId;
}
};
});
A part of index.html
<div ng-if="isAuthenticated() && displayProjectMenu == true" ng-controller="LocalMenuController">
<div local-menu></div>
</div>
Partial view localMenu :
<div class="sidebar content-box" style="display: block;">
<ul class="nav">
<li><i class="glyphicon glyphicon-list-alt"></i> Backlog</li>
<li><i class="glyphicon glyphicon-user"></i> My team </li>
</ul>
</div>
I'm trying to get the projectId from the $rootScope and inject it in the <a href="#/project/{{projectId}}" but I have some troubles. What's the way to do that ?

First of all, try using directives instead of ng-controller. You can encapsulate your code and template into a unit. You can also try creating a component. Pass some data to the directive/component and Angular will take care of updating the template and running whatever needs to run within the directive/component. (Given that you used two-way data-bindings)
From the code above, I cannot see what would trigger LocalMenuController to run again.

Related

AngularJS : ng-switch is not triggering when i was clicking second time?

I have a left nav in my one of the view of the application whiich is build using ng-repeat and ng-switch. every link's action associate to a directive in the right hand side. some time, the particular directive will include other directive when user click on the dropdown items from the current directive and page gets extended long and long , so if user want to go to the original state then he can click on the nav item from the left nav to refresh the page to the initial state of the directive. But whenever user clicks on the left nav second time when the left nav already selected, it is not get triggered.I want this get tirggered to bring my initial page of the RHS.
My highlevel code as follows
about.html
<div class="leftNav">
<ul class="nav myNav">
<li class="presentation" ng-repeat="link in links" ng-class="{link-active:currentLink=link.value==param}">
<a ng-href="#/home/{{link.value}}" ng-click="fetchLink(param)">{{link.title}}</a>
</li>
</ul>
</div>
<div ng-switch="fetchLink()">
<div ng-switch-when="About Us">
<div about-us></div>
</div>
<div ng-switch-when="Board Directors">
<div board-directors></div>
</div>
<div ng-switch-when="Our Impacts">
<div our-impacts></div>
</div>
</div>
aboutController.js
$scope.links = [{ title="About Us", value="about"},
{ title="Board Directors",value="board"},
{ title="Our Impacts", value="impact"} ];
var myParam =$root.current.params;
$scope.param = myParam.sec;
//sec has been configured in the route and get
// the values from user's input
$scope.fetchLink() = function() {
var retVal='';
var retVals = $.grep($scope.links, function(item,ind){
return item.value=$scope.param
});
if(retVals.length>0){
retVal = retVals[0].title;
}
return retVal;
};
};
On the router code of app.js
$routeProvider
.when('/about/:sec', {
templateUrl : 'app/view/about.html',
controller: 'aboutController.js'
});
}
When i click the second time, nothing get triggered and fetchLink() method is not triggered.

angular, access to scope outside of the ng-view wrapping div

I am trying to set up custom themeing on my app, so what I am doing is letting the user choose certain themes and it will change the apps theme holistically. I have a service which sends a piece of json and listens for it changing inside the controller of each view. Now this works fine within the view itself - for reference here's some snippets of the working code.
my factory controlling the theme -
angular.module('demoApp')
.factory('templatingFactory', function () {
var meaningOfLife =
{
'h1': '#ea6060',
'bg': '#ffffff'
};
return {
setTheme: function(theme) {
meaningOfLife = theme;
},
getTheme: function() {
return meaningOfLife;
}
};
});
One of my example controllers showing and changing the theme (and listening for changes)
$scope.themeStore = templatingFactory.getTheme();
console.log($scope.themeStore);
//send new themes
$scope.themeOne = function () {
var newT1 = { 'h1': '#8A6516',
'bg': '#000000'};
templatingFactory.setTheme(newT1);
};
$scope.themeTwo = function () {
var newT2 = { 'h1': '#ffffff',
'bg': '#ea6060'};
templatingFactory.setTheme(newT2);
};
$scope.themeThree = function () {
var newT3 = { 'h1': '#ea6060',
'bg': '#ffffff'};
templatingFactory.setTheme(newT3);
};
//listen for new themes
$scope.watchThemes = templatingFactory.getTheme();
$scope.$watch(templatingFactory.getTheme, function (newTheme) {
$scope.themeStore = newTheme;
});
and then on the template/view itself i do something like this -
<h3 ng-style="{ 'color' : themeStore.h1 }">Title</h3>
So my issue is that this works fine inside the view. However the ng-view tag is inside the body and outside of it are the body containers, as well as the header and footer menus that I would like to be able to hook onto with this theme object. So my quesiton is, is there any way to use that scope outside of the ng-view? I don't think it's possible but I'm not sure how else I could access and put a ng-style on the header footer and body to change some css on it with this method I am using.
So for a simple reference it looks like this -
<body ng-app="myApp">
<div class="container">
<div class="header" ng-style="{ 'background-color' : themeStore.bg }">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<i class="fa fa-bars"></i>
</button>
<div class="headerLogo"></div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
</ul>
</div>
</div>
<div ng-view class="velocity-opposites-transition-slideUpIn" data-velocity-opts="{ duration: 500 }" ng-style="{ 'background-color' : themeStore.bg }"> </div>
<div class="footer">
<p></p>
</div>
</div>
</body>
So as you can see - I'm trying to hook onto the header to change the background color, which does not work like this. What I noticed though, is if I put it on the ng-view div itself, it works alright.
I would much appreciate any input as I've been stuck on this for a while. Thank you for taking the time to read!
The DOM elements outside of your ng-view must have controllers of their own, with templatingFactory injected as a dependency.
First I would modify the html like so:
<div class="header" ng-controller="headerController" ng-style="{ 'background-color' : themeStore.bg }">
Then add headerController to your module:
angular.module('demoApp').controller('headerController', function($scope, templatingFactory){
$scope.themeStore = templatingFactory.getTheme();
$scope.$watch(templatingFactory.getTheme, function (newTheme) {
$scope.themeStore = newTheme;
});
});
A more reusable solution would be to create a directive that adds this controller functionality to whatever DOM element it is applied to, but the above is a little more straight forward.
I think the best way to have angular functions and variables outside ui-view or ng-view is to use a global service. in this case you should do your theming logic inside 'templatingFactory'. Then inject this service not in your controllers, but in your module.
angular.module('demoApp').run(['$rootScope', 'templatingFactory', function($rootScope, templatingFactory){
$rootScope.templatingService = templatingFactory;
}]);
So your service will be avaible in the $rootScope. now you can use it this way.
<body ng-app="myApp">
<div class="container">
<div class="header" ng-style="{ 'background-color' : templatingService.getTheme().bg }"> </div>
</div>
</div>
ps: I'm relative new in angular too, so I don't know nothing about good/wrong practices!
For the directive approach, a simple example might look something like this:
demoApp.directive('themeHeader', function (templatingFactory) {
return {
restrict: 'A',
link : function (scope, element, attrs) {
scope.$watch(templatingFactory.getTheme, function () {
element.css('background-color', newTheme.bg);
});
}
}
});
and the html would look like this:
<div theme-header>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"><i class="fa fa-bars"></i></button>
<div class="headerLogo"></div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right"></ul>
</div>

View different HTML pages?

I wanted to view different HTML pages based on what a user clicks. For example, I have three tabs set up as so:
<div class="span7" >
<ul class="nav nav-tabs" style="margin-bottom: 5px;">
<li class="active">First</li>
<li>Second</li>
<li>Third</li>
</ul>
<div class="span12" style="margin-left:0;" ng-grid="gridOptions"></div>
</div>
And I merely want to view a different page based off of what the individual clicks. For example, if he clicks First, he will see First's html page where source.sourceObject in the code below denotes which html page to view. It is written like so:
<div class="span5">
<div class="edus-activity-container">
<div ng-show="sourceViewState.selected" class="edus-admin-activities-grid" />
</div>
<div ng-include="'/partials/' + source.sourceObject + '.html'"/>
</div>
where in my javascript file, source.sourceObject is defined based off of if I click the First, Second or Third tab. However, my implementation is not working. I made sure I had no typos in the spelling of my files in source.sourceObject. Any ideas on how to do so?
In your controller:
var pages = { 'one': 'partials/one.html', 'two':'partials/two.html' }
$scope.currentPage = pages['one'] ; //This is required if you want a default page
$scope.first = function(){ $scope.currentPage = pages['one']; }
$scope.two = function(){ $scope.currentPage = pages['two']; }
In your template/HTML
<div ng-include="currentPage"/>

Ng-repeat not rendering content

I'm writing a web app using Node.js+Express to serve (with HoganJs as a templating engine) and AngularJS on the frontend. I'm having problems with ng-repeat rendering the correct number of elements, but without any content in. I broke the ng-repeat down into a smaller example and it's still not rendering.
EDIT: There was a typo in the Plunkr, so I removed it. Here's a more expanded extract from my app.
Here's a section of my view: index.hjs
<div class="search-results" ng-controller="results">
<ul class="tracks">
<li class="track" ng-repeat="track in tracks">
<ul class="meta">
<li>
<div class="name">
<span class="value">{{track.name}}</span>
</div>
</li>
<li>
<div class="album">Album:
<span class="value">{{track.album}}</span>
</div>
</li>
<li>
<div class="artist">Artist:
<span class="value">{{track.artist}}</span>
</div>
</li>
<li>
<div class="length">Length:
<span class="value">{{track.length}}</span>
</div>
</li>
</ul>
</li>
</ul>
</div>
The results controller: js/controllers/results.js
var results = function($scope, socket) {
$scope.tracks = [
{"uri":"spotify:track:1jdNcAD8Ir58RlsdGjJJdx","name":"Ho Hey","artist":"The Lumineers","album":"The Lumineers"},
{"uri":"spotify:track:3uuGbRzMsDI5RiKWKOjqWL","name":"Hey Porsche","artist":"Nelly","album":"Hey Porsche"},
{"uri":"spotify:track:5BSndweF91KDqyxANsZcQH","name":"Ho Hey","artist":"The Lumineers","album":"The Lumineers"},
{"uri":"spotify:track:2UNc0duOP4cS7gqYFFkwxT","name":"Hey Girl","artist":"Billy Currington","album":"Hey Girl"},
{"uri":"spotify:track:6fgbQt13JlpN59PytgTMsA","name":"Snow [Hey Oh]","artist":"Red Hot Chili Peppers","album":"Snow [Hey Oh]"}
];
socket.on("results", function(tracks) {
$scope.tracks = tracks;
console.dir(JSON.stringify($scope.tracks));
});
$scope.add = function(uri) {
socket.emit("add", uri);
};
};
And finally my module: app.js
var app = angular.module("app", []);
var factories = {
socket: socket
};
app.factory(factories);
var controllers = {
actions: actions,
search: search,
results: results,
queue: queue
};
app.controller(controllers);
For testing purposes, the tracks are hardcoded in when the app is run 5 lis are rendered but there no content has been templated inside of them.
Remove a ) here:
];
});
^
Plnkr: http://plnkr.co/edit/e0URFt?p=preview
I've just realised what's happening here. Hogan.js is overwriting angular's templates when the page is rendered at the server.
Just remove the extra bracket added to your script (line 19). Please look at the script here.
http://plnkr.co/edit/sy2m0RuXRudGvjnmfC3Y?p=preview

AngularJS update model on click of element and also toggle CSS class

New to Angular and a bit confused. I have a list item that needs to display a tick or a cross depending on an initial value from its controller.
When a user clicks the list item I want to change the value to its current opposite and then update the CSS class to reflect this in the DOM.
Currently I have the following controller:
app.controller('SetupSettingsCtrl', ['$scope', '$rootScope', '$location', function ($scope, $rootScope, $location) {
console.log('setup controller loaded');
$scope.data ={
about: {
uie: '439213949123I034',
appVersion: '3.23453'
},
lab: {
sleep: false,
move: true
},
stats: {
optOut: true
}
};
$scope.chkItem = function($event, prop){
console.log(prop);
};
}]);
And the following template partial:
<div class="pure-u-1">
<h1 class="h2 text-center">About</h1>
<p class="text-center">Phone UIE: <span class="text-valid">{{uie}}</span></p>
<p class="text-center">App version: <span class="text-valid">{{appV}}</span></p>
<p class="text-center"><i class="icon-refresh"></i> Manual Update</p>
</div>
<div class="pure-u-1">
<h2 class="text-center">LAB functions</h2>
<section class="view-content">
<ul class="center-block list-bare list-icon-box-chk">
<li class="pointer" ng-class="{'un-chk': !sleep}" ng-model="sleep" ng-click="chkItem($event)">Sleep with phone on bed</li>
<li class="pointer" ng-class="{'un-chk': !move}" ng-model="move" ng-click="chkItem($event)">Movement checker</li>
</ul>
</section>
</div>
<div class="pure-u-1">
<h2 class="text-center">Anonymous Statistics</h2>
<section class="view-content">
<ul class="center-block list-bare list-icon-box-chk">
<li class="pointer" ng-class="{'un-chk': !optOut}" ng-model="optOut" ng-click="chkItem($event)">I do not want anonymous statistics to be geathered for Health research, and healthcare improvement</li>
</ul>
</section>
</div>
I do not now how to pass the model reference to update the $scope value to trigger the change? When I pass the model property reference I get the value.
I need to call the controller method to pass the model value to the server also.
You should do both: toggle the model as well as call the function inside ng-click without the need of passing the model as a parameter. Also you dont need to bind the model to the lis:
<li class="pointer"
ng-class="{'un-chk': !data.lab.sleep, 'chk': data.lab.sleep}"
ng-click="data.lab.sleep = !data.lab.sleep; chkItem($event)">
Sleep with phone on bed
</li>
<li class="pointer"
ng-class="{'un-chk': !data.lab.move, 'chk': data.lab.move}"
ng-click="data.lab.move = !data.lab.move; chkItem($event)">
Movement checker
</li>
(I guess those {{uie}} and {{appV}} in your HTML need to be like {{data.about.uie}} and {{data.about.appVersion}})
JS:
$scope.chkItem = function($event){
/* do something here */
};
In your "Controller" it will be avaliable
$scope.chkItem = function($event, prop){
console.log(data.lab.sleep);
};
You can update directly no need to pass
<li class="pointer" ng-class="{'un-chk': !data.lab.sleep}" ng-model="data.lab.sleep" ng-click="chkItem($event)">Sleep with phone on bed</li>

Categories