template not displaying binded data after routed, on first click - AngularJS - angularjs

Trying to route to different view template from the index page. Initially, the list on main index page gets loaded and the main.html gets loaded in ng-view, displaying it's text contents. The data from 'MainCtrl' is broadcasted properly and works fine. Now, the confusion is, when the item from the list is clicked, it gets routed to content template(content.html), but the content does not display the binded value on the first click on the list. But, after second click, it starts showing the binded values that is broadcasted from MainCtrl.
<body ng-app="myApp">
<div ng-controller="MainCtrl">
<ul ng-repeat="value in msg" ng-click="setSelectedValue(value)">
<li>
<a href='#/content'>{{ value }}</a>
</li>
</ul>
</div>
<div ng-view=""></div>
main.html:
<p>Select from the list.</p>
content.html:
//loads the selected item from the list on index page
<h3>Selected: {{ message }}</h3>
angular
.module('myApp', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/content', {
controller: 'ContentCtrl',
templateUrl: 'views/content.html'
})
.otherwise({
redirectTo: '/'
});
})
.factory('myService', function($http, $rootScope){
var sharedService ={};
sharedService.message = '';
sharedService.prepforBroadcast = function(value){
this.message = value;
this.broadcastItem();
};
sharedService.broadcastItem = function(){
$rootScope.$broadcast ('handleBroadcast');
};
return {
sharedService: sharedService
};
})
.controller('MainCtrl', function ($scope, myService) {
$scope.msg = data; //this will be json data
$scope.selectedValue;
$scope.setSelectedValue = function(value){
$scope.selectedValue = value;
myService.sharedService.prepforBroadcast(value);
}
})
.controller('ContentCtrl', function ($scope, myService) {
$scope.$on('handleBroadcast', function(){
$scope.message = myService.sharedService.message;
})
});
Not sure what exactly is the reason for not binding the data on the very first click even though when the template loads instantly. Any help or thought would be greatly appreciated. Scratching my head for a while.

<ul ng-repeat="value in msg" ng-click="setSelectedValue(value)">
check with out ng-click="setSelectedValue(value)" part. seems like ur click is going to handle by setSelectedValue(value) function

The ng-repeat and ng-click should be on li.
<ul>
<li ng-repeat="value in msg" ng-click="setSelectedValue(value)">
<a href='#/content'>{{ value }}</a>
</li>
</ul>

Related

angularjs ngroute not working

i am new in angularjs i have a index page with some data with anchor tag when user click in a particular anchor tag page redirect to list page and show data but ngRoute not working and also the not getting the query string value. Where i wrong
this is my index page
<div class="all_cat" ng-repeat="state in statelist">
<h2>{{state.Statename}}</h2>
<div class="cat-col-4" ng-repeat="citylist in state.city">
<ul>
<li><i class="fa fa-caret-right"></i>{{citylist.cityname}} ({{citylist.jobcount}})</li>
</ul>
</div>
<div class="clear"></div>
</div>
and this is my js
var app = angular.module('angularTable', ['ngSanitize', 'ui.select', 'angularTrix', 'ngRoute']);
app.config(function($routeProvider) {
debugger;
$routeProvider
.when('/JobList:ID', {
templateUrl: 'job/JobList.cshtml',
controller: 'joblist'
})
});
app.controller('joblist', function($scope, $routeParams) {
debugger;
$scope.message = 'Clicked person name from home page should be display here';
$scope.person = $routeParams.ID;
});
i am not under stand where i do wrong
Ass braja lal Mahanty tell you might want /JobList/:ID instead of /JobList:ID.
So you have to set state as:
$routeProvider
.when('/JobList/:ID', {
templateUrl: 'job/JobList.cshtml',
controller: 'joblist'
})
});

How to set active class on the current state using angular-route?

my route file
app.config(["$routeProvider",function($route)
{
$route.when("/",{
templateUrl : "partials/index.html",
controller : "AppCtrl"
}).when("/contact",{
templateUrl:"partials/contact.html",
controller:"ContactCtrl"
}).
when("/about-us",{
templateUrl:"partials/about.html",
controller:"AboutCtrl"
}).
when("/gallery",{
templateUrl:"partials/gallery.html",
controller:"GalleryCtrl"
}).
otherwise({
redirectTo:"/"
});
}]);
in my header.html partials i'm using HeaderCtrl controller
app.controller("HeaderCtrl",["$scope","$location",function($scope,$location)
{
$scope.location=$location.path().replace("/","");
}]);
my header.html
<ul ng-controller="HeaderCtrl">
<li ng-class="{active:location===''}">home</li>
<li ng-class="{active:location==='about-us'}">about us</li>
<li ng-class="{active:location==='gallery'}">gallery</li>
<li ng-class="{active:location==='contact'}">contact</li>
</ul>
when the page reloads (actual refresh) then it works ie the class active is applied on the respective li but when i change the routes (by clicking on the menu items) it doesn't work
The solution to your problem is to bind an event that updates $scope.location when the URL successfully changes. You don't have to bind a click event to each <li> element. What if the route is invalid or fails? You don't want to show the user that element is the active route when it's really not.
If you read the documentation on the $location service, you'll see an events section. The one we're interested in is $locationChangeSuccess. To wire it up in your controller, do this:
$scope.$on('$locationChangeSuccess', function () {
$scope.location = $location.path().replace('/', '');
});
you add some object like active to router and set condition on your html with ngClass
like this :
app.config(["$routeProvider",function($route)
{
$route.when("/",{
templateUrl : "partials/index.html",
controller : "AppCtrl",
active:'home',
}).when("/contact",{
templateUrl:"partials/contact.html",
controller:"ContactCtrl",
active:'contact',
}).
when("/about-us",{
templateUrl:"partials/about.html",
controller:"AboutCtrl",
active:'about',
}).
when("/gallery",{
templateUrl:"partials/gallery.html",
controller:"GalleryCtrl"
active:'GalleryCtrl',
}).
otherwise({
redirectTo:"/"
});
}])
//remember that add $route inside the scope
.controller("HeaderCtrl",["$scope","$location",function($scope,$route)
{
$scope.$route = $route;
}]);
.active{
color:#a33;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<ul ng-controller="HeaderCtrl">
<li data-ng-class="{'active':$route.current.active === 'home'}">home</li>
<li data-ng-class="{'active':$route.current.active === 'about'}">about us</li>
<li data-ng-class="{'active':$route.current.active === 'gallery'}">gallery</li>
<li data-ng-class="{'active':$route.current.active === 'contact'}">contact</li>
</ul>

ng-class not evaluating to true

I have some html with which I'm trying to use ng-class. If I just hardcode in "true", my CSS for the class is applied as expected. But, as soon as I replace the true with an expression (shown below), it seems my class isn't being applied. Here is the line of HTML:
<li ng-repeat="menuItem in menuItems"><span ng-class="{active: $index==activeIndex}" class="underline"><a ng-href={{menuItem.itemLink}}>{{menuItem.itemName}}</a></span></li>
And the code from the controller:
$scope.$on('$routeChangeSuccess', function(index){
$scope.activeIndex = index;
console.log("Set Active Index");
});
It seems the index param of the '$routeChangeSuccess' event callback is not a number as you expected.
If you want to change your actived list when route change. you can pass $location service to $scope.
here is example: http://jsfiddle.net/yRHwm/4/
HTML code:
<div ng-app="myapp">
<div class="container" ng-controller="MyCtrl">
<li ng-repeat="menuItem in menuItems">
<!-- use $location.path() to detect current path -->
<span ng-class="{'active': menuItem.itemLink==$location.path()}" class="underline">
<a ng-href="#{{menuItem.itemLink}}">{{menuItem.itemName}}</a>
</span>
</li>
</div>
<div ng-view></div>
</div>
Javscript Code:
angular.module('myapp', ['ngRoute'])
.config(function($routeProvider){
$routeProvider
.when('/1', {controller:'firstController'})
.when('/2', {controller:'secondController'})
})
.controller('MyCtrl', function($scope, $location) {
$scope.menuItems = [
{itemLink: '/1', itemName: 'Link1'},
{itemLink: '/2', itemName: 'Link2'}
];
// pass $location service to scope, then you can use $location.path() to detect current path
$scope.$location = $location;
// this is no longer used. just to show index is not a number
$scope.$on('$routeChangeSuccess', function(index){
$scope.activeIndex = index;
// you can see in the console which index is not a number.
console.log("Set Active Index", index);
});
})
.controller('firstController', function($scope){
console.log('first');
})
.controller('secondController', function($scope){
console.log('second');
});

routeProvider in angularJS not acting right

Within my view I am outputting links. When I go to click a link it triggers the otherwise method in my routeProvider and ends up redirecting back to home. I need it to redirect indiv id and I need to be able to grab project.id from my view within my controller. May I please have some assistance. I'm kind of stuck.
My view:
<div class="container clearfix">
<div class="pagename sixteen columns fadeInUp animated">
<h1 style="font-family: Merriweather">Portfolio</h1>
</div>
</div>
<div class="container clearfix" ng-controller="portfolioController">
<ul style="padding-left: 20pt" class="large-block-grid-4 align-center">
<li class="part" ng-repeat="project in projects">
<a href="#/indiv?id={{ project.id }}">
<img src="{{ project.screenshot_uri }}" alt="">
</a>
<br><br>
<h4>{{ project.project_name }}</h4>
<p>{{ project.description }}</p>
</li>
</ul>
</div><br><br>
My app data:
var app = angular.module("app", ['ngRoute']).config(function($httpProvider, $routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'index.php/projects/projects/home',
controller: 'homeController'
});
$routeProvider.when('/portfolio', {
templateUrl: 'index.php/projects/projects/portfolio',
controller: 'portfolioController'
});
$routeProvider.when('/indiv:id', {
templateUrl: 'index.php/projects/projects/indiv',
controller: 'indiv_controller'
});
$routeProvider.when('/contact', {
templateUrl: 'index.php/projects/projects/contact',
controller: 'contactController'
});
$routeProvider.otherwise({ redirectTo: '/home' });
});
app.factory('pull_projects', function($http) {
return {
get_projects: function(callback) {
$http.get('index.php/projects/pull_projects').success(callback);
}
};
});
app.controller('portfolioController', function($http, $location, $scope, pull_projects) {
pull_projects.get_projects(function(results) {
$scope.projects = results;
});
});
app.controller('contactController', function($http, $location, $scope) {
});
app.controller('indiv_controller', function($http, $location, $scope, $routeParams) {
alert($routeParams.id);
});
app.controller('homeController', function($http, $location, $scope) {
});
Seems the problem is that you are defining the angular routing url and the url in the markup slightly different.
Route:
In the route url you are defining /indiv:id. However, this would match a url where the id was part of the indiv part. So, http://host/indiv123.
So, I would suggest changing this to: /indiv/:id. This will then match urls like this: http://host/indiv/123.
Markup:
In the HTML you are declaring the url as #/indiv?id={{ project.id }}. This will produce the url: /indiv?id=123.
To match our new angular route we need the template to be #/indiv/{{ project.id }} so that we produce a url like /indiv/123.
Hope this helps.
You should use :
ng-href="#/indiv?id={{ project.id }}"
instead of
href="#/indiv?id={{ project.id }}"
This ensures that {{ project.id }} is correctly resolved before it is used as a link.
This occurs because Angular not always gets the chance to intercept the data binding requests before the browser attempts to resolve href and src (<img src="">) attributes. Accordingly, you should use ng-src for images.

AngularJS $location.path() changed after upgrading to 1.1.15

I have a NavigationController that has a selectedItem for the current selected item in a navigation list. It uses $location.path() to try and set it to a default value. It's in hashbang mode. Here is a simplified version:
App.controller("NavigationController", ['$scope', '$location', function($scope, $location) {
$scope.currentSelection = $location.path() || "/dashboard";
$scope.select = function( name ) {
$scope.currentSelection = name;
}
}]);
And the html:
<body ng-app="App">
<div class="container-fluid absoluteFill">
<div class="row-fluid fill" ng-controller="NavigationController">
<div class="span2 nav-bubble fill">
<ul class="nav nav-list">
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
</div>
<div ng-view></div>
</div>
</div>
</body>
And the config:
angular.module("App", ["ngResource"])
.config(function($routeProvider) {
$routeProvider.
when( '/', { redirectTo: '/dashboard' }).
when( '/dashboard', {
controller: 'DashboardController',
templateUrl: '/gpa/app/views/dashboard.html'
}).
otherwise({redirectTo: '/'});
})
The problem is that when I navigate to /home/index (without a hash bang) $location.path() returns "/index" where it used to return null prior to 1.1.15. However, if I go to "/home/index#/dashboard it returns "/dashboard" as expected. I tried redirecting when someone goes to "/" to "/dashboard", but NavigationController is called prior to being redirected so it continues to get "/index".
So how can I at least tell when the hashbang is not included? $location.hash() always seems to return "". I don't want to hard code "/index" in my code to know when nothing is on the URL.
I think you want to use the $route service and hook into the $routeChangeSuccess event.
App.controller("NavigationController", function($scope, $location) {
$scope.$on("$routeChangeSuccess", function (scope, next, current) {
$scope.currentSelection = $location.path() || "/dashboard";
});
$scope.select = function( name ) {
$scope.currentSelection = name;
}
});

Resources