`ng-class` not working on functional call from included template - javascript

I have my main template called home.html, the controller is homeController applied throw :
$routeProvider :
$routeProvider
.when ("/", {
templateUrl : "views/home.html",
controller : "homeController"
});
$routeProvider
.otherwise ({
redirectTo:'/'
});
works fine. I have seperate html template for header' which included in thehome.html` like this:
<div class="content">
<ng-include src="'/views/header.html'"></ng-include>
<div class="globe">
<div class="progName">
<div class="swiper"></div>
<h2 class="active">
<span class="title">
{{activeApp.name}}
</span>
<span class="note">{{activeApp.note}}</span>
</h2>
<h2 class="que t{{$index+1}}" ng-click="activate(app)" ng-repeat="app in queApp">{{app.name}}</h2>
</div>
for the header i have seperate controller called 'header.jswhich is included in theindex.html` file.
<script src="app.js"></script>
<script src="js/script/factory/server.js"></script>
<script src="js/script/controllers/header.js"></script>
<script src="js/script/controllers/homeController.js"></script>
<script src="js/script/directives/home/programNames.js"></script>
In the header, there is a class, i want to apply by conditionally, so i added the condition in the header.html file (which is included)
in the header.js (headerController) I am trying to add the conditonal class, but not working:
my header.js:
angular.module("tcpApp")
.controller('header', ['$scope', function ($scope) {
$scope.show = false;
$scope.menuHandler = function () {
$scope.show = !$scope.show;
console.log("i am called");
}
}]);
What i am missing here? the way i am adding the controller is wrong? or i need to write the function withing parent controller homeController itself?
can't I keep seperate controller for header and include with other template?
Andy one help me handle?
Thanks in advance.
UPDATE
Header html :
<header ng-controller="header" >
<h1>TCP</h1>
<nav>
<a class="menu" ng-click="menuHandler()" href="#">Menu</a>
<span ng-class="{'activate':show}">
<span>All</span>
<span>Important</span>
<span>Design</span>
<span>Supply</span>
<span>Contruction</span>
<span>Issue Log</span>
</span>
</nav>
</header>

Try something like this in your home.html :
<div class="content">
<ng-include src="views/header.html"></ng-include>
//code here
</div>
Remove the '/' at the starting of the path of header.html template.
This should do the trick, I guess.

try something like this:
<span ng-class="show?'activate':'other-class'">

the problem is, I am using a module for scroll purpose. when i comment that, it works.
var newHash = 'anchor3';
if ($location.hash() !== newHash) {
$location.hash('anchor3');
} else {
$anchorScroll();
}
I commented all above. thanks every one!

Related

Web Page not Anchoring in Angular

I am attempting to have the page go to a div section of the page based on what they click. I have the div for each section id'd with the proper tag. I have done a test where I can load the page and type url.com/services#insertidhere and it will go to the correct location. The issue is when I try to implement it in the state it won't go to the location. It just goes to the page normally even though the URL shown is correct.
HTML Index Snippet
<div ng-repeat="x in blue.services">
<div class="wrapIMG">
<img src="{{x.icon}}" />
<img class="clone" src="{{x.icon}}" />
</div>
<h4>{{x.title}}</h4>
<hr/>
<p>{{x.text}}</p>
<a ui-sref="services({id: x.title})" class="button2">About This</a>
</div>
myapp.js Snippet
app.config(function($stateProvider){
$stateProvider
.state('index', {
url:"/",
templateUrl: 'main.html',
data: {
cssId: 'home'
}
})
.state('services', {
url: "/services/#:id",
templateUrl: 'services.html',
data: {
cssId: 'services'
}
})
});
Services HTML Snippet
<section class="no-padding" style="" id="[id equal to x.title]"> ...</section>
<section class="no-padding" style="" id="[id equal to x.title]"> ...</section>
<section class="no-padding" style="" id="[id equal to x.title]"> ...</section>
I believe the issue has to be with .state URL but it shows correctly in the URL but it just isn't going to the location.
Angular uses the # in URLs for page routing (so do many other SPA frameworks).
To anchor the link to a specific id on a page, use the $anchorScroll service.
Example:
<div id="scrollArea" ng-controller="ScrollController">
<a ng-click="gotoBottom()">Go to bottom</a>
<a id="bottom"></a> You're at the bottom!
</div>
<script>
angular.module('anchorScrollExample', [])
.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
function($scope, $location, $anchorScroll) {
$scope.gotoBottom = function() {
// set the location.hash to the id of
// the element you wish to scroll to.
$location.hash('bottom');
// call $anchorScroll()
$anchorScroll();
};
}]);
</script>
$scope.toPage = function(){$state.go('index');}
Did you try this?

Change div content dynamically on ng-click AngularJS

I want to display some data and tables in the content div which depends on which category you choose on the left hand side navigation.
So if I change the category also the displayed content of the content div should change.
Here is my code on Plunkr.
But it seems that not even this simple example is working.
So I have two Questions:
1.) How can I fix this example code to run ?
But more important:
2.) Is there a better way to change the content div when you change the category ?
I removed 'this' elements from code and also changed ng-view to ng-show.
<div>
<div ng-show="showApple">{{content}}</div>
<div ng-show="showBanana">{{content}}</div>
<div ng-show="showOrange">{{content}}</div>
</div>
There was something wrong with that you named your div class "content" so I removed that also.
I am sure it isn't a perfect solution but now it works.
link to plnkr
To be honest your best bet is to use $states/views. With a data-ui-view on the content div and a data-ui-sref link on the button on your menu, you can easily switch out content. Take a look at the ui-router page to get a better understanding of it. With templates for each 'view' that your menu will click to, your code will not just be much easier to manage, but probably more understandable.
You can use ng-include to show your contents but you have to keep them in seperate files e.g contentForApple, contentForBanana and contentForOrange.
Here I can show you a little change in your div
<div class="content">
<div ng-show="MainCtrl.showApple" ng-include ="'contentForApple.html'"></div>
<div ng-show="MainCtrl.showBanana" ng-include = "'contentForBanana.html'"></div>
<div ng-show="MainCtrl.showOrange" ng-include = "'contentForOrange.html'"></div>
</div>
Hope this help you. Take one json array for category and data and get details of json data which index is clicked
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="MyController">
<div class="container">
<div class="row">
<div class="col-lg-3">
<ANY ng-repeat="x in category" ng-click="getData($index)">
{{x.category}}<br>
</ANY>
</div>
<div class="col-lg-6">
{{data}}
</div>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('MyController', function ($scope)
{
$scope.data = '';
$scope.category = [{category:'Apple',data:'Apple Data'},{category:'Banana',data:'Banana Data'},{category:'Orange',data:'Orange Data'}];
$scope.getData = function(index)
{
$scope.data = $scope.category[index]['data'];
}
});
</script>
</body>
</html>
I did it with simple ngif
1) Keep an Index of Page which needs to be is loaded now
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.pageIndex = 0;
/*
* Updates current Page index
*/
$scope.changeIndex= function(indexToChange){
$scope.pageIndex = indexToChange;
}
});
2) Load content based on selected index
<body ng-controller="MainCtrl">
<div class="mainframe">
<div class="navigation">
<ul class="list-group">
<li class="list-group-item" ng-click="changeIndex(0)">Home<span class="status-icon"></span></li>
<li class="list-group-item" ng-click="changeIndex(1)">Sign Up<span class="status-icon"></span></li>
<li class="list-group-item" ng-click="changeIndex(2)">About<span class="status-icon"></span></li>
</ul>
</div>
<div class="content">
<div ng-if="pageIndex == 0" ng-include ="'Home.html'"></div>
<div ng-if="pageIndex == 1" ng-include = "'SignUp.html'"></div>
<div ng-if="pageIndex == 2" ng-include = "'About.html'"></div>
</div>
</div>
Final Result:
https://embed.plnkr.co/ic0eY2vwiOnChN2ahrEt/

How do i define routing to navigate to details page when link clicked

I need some help to implement list and details page.
I have motorList.html page where i am listing all motors as hyperlink retrieved from server (database).
motorList.html
<div>
<ul class="phones">
<li ng-repeat="motor in motors" >
<a href="#/motors/{{motor.Id}}">{{motor.Name}}
</li>
</ul>
</div>
I want when user clicks on any motor link, system should navigate to motorDetails.html page and show the details for clicked/selected motor.
For this i defined my routes as following in app.js
app.js
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/motors', {
templateUrl: 'View/motorlist.html',
controller: 'motorController'
}).
when('/motors/:motorId', {
templateUrl: 'View/motordetail.html',
controller: 'motorDetailsController'
}).
otherwise({
redirectTo: '/motors'
});
}]);
motorDetails.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<ul class="phones">
<li ng-repeat="motor in motors" class="thumbnail">
<p>{{motor.Name}} {{motor.Make}} {{motor.Model}} {{motor.Year}} {{motor.Kilometers}} {{motor.Price}} {{motor.Color}} {{motor.SellerType}}</p>
</li>
</ul>
</div>
</body>
</html>
motorDetailsController.js
var app = angular.module('myApp', ['ngSanitize', 'ui.select']);
app.controller('motorDetailsController', function ($scope, $routeParams, motorService) {
$scope.motors = null;
$scope.getMotorDetails = function (Id) {
motorService.getByMake(Id)
.success(function (motors) {
$scope.motors = motors;
})
.error(function (error) {
$scope.status = 'Unable to load motor data: ' + error.message;
});
}
});
Problem:
When i click on any motor hyperlink, it does not navigate to motorDetails.html page but url changes e.g. http://localhost:12270/View/motorList.html#/motors/161.
I am new to AngularJs routing and for sure i am missing something here but not sure what is wrong.
Could anyone guide me please.
Thanks
You should add ng-view directive on your page, which will show the template loaded from the $routeProvider by watching the URL. You need to add ng-view directive somewhere in your body.
Additionally you should incorporate the changes suggested by #Dvir.
Markup
<body>
<div>
<ul class="phones">
<li ng-repeat="motor in motors" class="thumbnail">
<p>{{motor.Name}} {{motor.Make}} {{motor.Model}} {{motor.Year}} {{motor.Kilometers}} {{motor.Price}} {{motor.Color}} {{motor.SellerType}}</p>
</li>
</ul>
</div>
<div ng-view></div>
</body>
Update
Ideally you should have ng-view directive there in motorList.html, which gets loaded(But I'm treating it as the index.html page where all the css & js references are there)
Also you don't need to include the html, head & body tag in partial as its going to treated as partial, So remove body,head & html tag and make it simple by placing required template only.
motorDetails.html
<div>
<ul class="phones">
<li ng-repeat="motor in motors" class="thumbnail">
<p>{{motor.Name}} {{motor.Make}} {{motor.Model}} {{motor.Year}} {{motor.Kilometers}} {{motor.Price}} {{motor.Color}} {{motor.SellerType}}</p>
</li>
</ul>
</div>
That's because href is a regular attribute and it's not evaluated by angularJs.
To make this expression to be your desired link you have to use ng-href so angularJs will evaulate the expression and assign it to an href html attirbute.
You have to change
href="#/motors/{{motor.Id}}"
to
ng-href="#/motors/{{motor.Id}}"
In addition to get its id. you have to use $routeParams in the controller.
For instance:
var id = $routeParams.motorId
UPDATE
I missed that but #Pankaj Parkar right. You have to use ng-view to make the routeProvider to assign the relevant view to the right placeholder.
How to use ng-view ?
You have to make an element where do you want to make the view appear.
It can be part of the page or all the page.
Put the element wherever you want and you'll understand.
For instance:
<body>
<div id="nav">
</div>
<ng-view>
<!-- this is the place your html template will apear -->
</ng-view>
</body>

Angular1.3: Access functions from standard controllers, inside a view which uses controllerAs?

I have a simple controller defined in my main app.js file, which controls opening/closing of my navbar and is visible on all other views of my app:
app.js:
.controller('mainController', ['$scope', function($scope){
$scope.menuActive = false;
$scope.toggleMenu = function(){
$scope.menuActive = !$scope.menuActive;
}
}]);
index.html:
<nav class="side-menu" ng-class="{ 'side-menu-open' : menuActive }">
<ul>
<li>LINK1</li>
<li>LINK2</li>
</ul>
</nav>
<!--Other views::.....-->
<div ui-view></div>
All my other views(which use controllerAs), have a button with an ng-click which I am using to access the above $scope.toggleMenu() function and ng-class, but this does not work, and I don't get any errors either:
view1.html :
<span class="btn btn-default"
ng-click="toggleMenu()">
MENU
</span>
View1.js:
angular
.module('myApp.view1', [])
.controller('View1Ctrl', [
function(){
................
}
]);
Also, the reason I have done it this way again is because my navbar is persistent throughout my app. Does this go against best practices by any chance?
If you are using the .. controller as .. syntax, make sure that you are using it for all controllers. Don't be selective about it.
Next, when using the syntax, you need not inject the $scope object. You need to instead use the this variable and attach any properties or functions that you would normally associate with the $scope object with the this object instead.
Thus,
$scope.toggleMenu = function(){
$scope.menuActive = !$scope.menuActive;
}
becomes
this.toggleMenu = function(){
this.menuActive = !this.menuActive;
}
Finally in your view, be sure to associate each expression with a controller.
<div ng-controller="mainController as main">
<nav class="side-menu" ng-class="{ 'side-menu-open' : main.menuActive }">
<ul>
<li>LINK1</li>
<li>LINK2</li>
</ul>
</nav>
<div ui-view>
<!-- Assuming that the following gets compiled to ui-view -->
<span class="btn btn-default" ng-click="main.toggleMenu()">
MENU
</span>
</div>
</div>
You can get some further hints on using the controller as syntax here

In Angular ui-router nested state url changes,but template is not loading

I am using ui-router for nested states & views. When I click on the link, the URL changes to the URL for the substate, but the template does not load.
For example, when the URL changes to the substate project/settings, the corresponding template project.settings.html is not loading.
Here is an SSCCE courtesy of Plunkr
Below is my code as well:
app.js
myApp.config(function ($stateProvider, $urlRouterProvider){
$stateProvider
.state('project', {
url: "/project",
views:{
"content":{templateUrl: "partials/project.html"},
"header":{templateUrl: "partials/header"}
}
})
.state('project.settings', {
url: "/settings",
views:{
"content":{templateUrl: "partials/project.settings.html"},
"header":{templateUrl: "partials/header"}
}
})
$urlRouterProvider.otherwise("/")
});
/* cheching whether the user is authentic or not*/
myApp.run(function($rootScope,$location,$cookieStore,validateCookie,$state) {
$rootScope.$on('$stateChangeStart',function(event,toState,toParams,fromState){
if($cookieStore.get('user')){
validateCookie.authService(function(result,error){
if(!result){
$location.path("/");
}else{
$state.go('project.settings');
}
});
}
else{
$location.path("/");
}
});
});
index.html
<div ng-controller="userController">
<div ui-view="header"></div>
<div class="container" ui-view="content"></div>
</div>
project.html
<div ng-controller="userController">
<div class="details">
<a ui-sref=".settings" class="btn btn-primary">Settings</a>
</div>
</div>
project.settings.html
<h1>Project Setting -State test</h1>
Your nested project.settings state needs to address the view in the higher state explicitly using an '#' suffix, ie.:
.state('project.settings', {
url: "/settings",
views:{
"content#":{templateUrl: "partials/project.settings.html"},
"header#":{templateUrl: "partials/header"}
}
})
See more details here https://github.com/angular-ui/ui-router/wiki/Multiple-Named-Views#view-names---relative-vs-absolute-names
First of all change file name project.settings.html in templateurl and file name to projectSettings.html (remove dot).
.state('project.settings', {
url: "/settings",
views:{
"content":{templateUrl: "partials/projectSettings.html"},
"header":{templateUrl: "partials/header"}
}
})
Add two divs in the project template to load the sub pages (header abd projectSettings)
Note: Any content in this divs will be replaced with the page loaded here.
project.html
<div ng-controller="userController">
<div class="details">
<a ui-sref=".settings" class="btn btn-primary">Settings</a>
</div>
<div ui-view="header">( Project Page header will replace with projectSettings header )</div>
<div class="container" ui-view="content">( Project Page content will replace with projectSettings Content )</div>
</div>
I had the same issue and the solution was to place ui-view to your parent's template. Because your partials also need a too, if they will be loading a template from a child state.
See here https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#issue-my-templates-are-not-appearing--loading--showing
If using nested views with UI-router, be sure to add ui-view into the html of the parent page and include specific named views.
I had the same issue, the solution was; open the project.html file (which is the parent page) and wrap everything within <ui-view>
So, replace these:
<div ng-controller="userController">
<div class="details">
<a ui-sref=".settings" class="btn btn-primary">Settings</a>
</div>
</div>
with these:
<ui-view>
<div ng-controller="userController">
<div class="details">
<a ui-sref=".settings" class="btn btn-primary">Settings</a>
</div>
</div>
</ui-view>
and you will be good to go ;)
Use ui-sref="project.settings" for link in project.html template.

Categories

Resources