Routes: controller doesn't get called - angularjs

I have three files:
index.html
players.html
app.js
index.html: pretty simple.
<body>
<main ng-view></main>
</body>
players.html: which should display a list of players.
<section>
<ul>
<li ng-repeat="player in players">
<h4>{{player}}</h4>
</li>
</ul>
</section>
app.js: which contains a route to /players and controller that has a list of players to be displayed on the view.
// Module
const myApp = angular.module('myApp', ['ngRoute']);
myApp.config(['$routeProvider', $routeProvider => {
$routeProvider
.when('/players', {
controller: 'playersController',
templateUrl: 'views/players.html'
})
}]);
// Controller
myApp.controller('playersController', ['$scope', $scope => {
$scope.players = ['Kaka', 'Maldini', 'Nesta'];
}]);
When I route to '/players', the controller doesn't get called and nothing displays, however when I use ng-include instead and add the controller as an attribute, it works fine.

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'
})
});

Scope doesn't work

I'd like to set a scope for a different route but it seems not working...
var app = angular.module('AngularApp', ['ngRoute', 'ngAnimate']);
app.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'menu.html',
controller: 'MenuController'
}).when('/slides/:menuItem', {
templateUrl: 'slides.html',
controller: 'SlidesController'
});
});
app.controller('MenuController', function($scope, $http) {
$http.get('database.json').then(function(response) {
$scope.bottomBar = 'no';
$scope.pageClass = 'menus';
$scope.database = response.data;
});
});
app.controller('SlidesController', function($scope, $http, $routeParams) {
$http.get('database.json').then(function(response) {
$scope.bottomBar = 'yes';
$scope.pageClass = 'slides';
$scope.database = _.find(response.data.menuItems, {'url': $routeParams.menuItem});
});
});
<body ng-app="AngularApp">
<div class="line">
<div class="col-12">
<img src="images/logo.jpg">
</div>
</div>
<div class="page {{pageClass}}" ng-view></div>
<div class="bottom-bar">
<ul>
<li>Retour {{bottomBar}}</li>
</ul>
</div>
</body>
bottomBar is empty...
Looks like you are putting html in app directly.
You can move below code in a template and use ng-include to add this template in you all views.
<div class="bottom-bar">
<ul>
<li>Retour {{bottomBar}}</li>
</ul>
</div>
This is because your controller scope is present in this div with ngView. Therefore anything outside this div won't have scope binding.
<div class="page {{pageClass}}" ng-view></div> <!-- controller active here only -->

AnguarJS Routing Not Working As Expected

I have a listing of blog posts and I want to be able to click on the title and have it dynamically redirect to the proper posting.
So far it works except when I click on the anchor tagged title it redirects to:
blog/#/post/:post
rather than
blog#/post/:post
I've tried to change the href to data-ng-href,
using target="_self"
and tried changing the href="#/post/{{post}}" and href="/post/{{post}}"
Routes:
(function(){
'use strict';
angular.module('ghpg')
.config(Config);
Config.$inject = ['$routeProvider'];
function Config($routeProvider){
$routeProvider
.when('/listing', {
templateUrl: '/angular/views/listing.client.view.html'
}).otherwise({
redirectTo:'/'
}).when('/post/:title',{
templateUrl: '/angular/views/post.client.view.html',
controller: 'postController',
controllerAs: 'post'
}).otherwise({
redirectTo:'/listing'
});
}
})();
Listing View:
(function(){
'use strict';
angular
.module('ghpg')
.controller('listingController', listingController);
listingController.$inject = ['$scope', 'blogContent'];//,'blogContent'] //, 'blogContent'];
////
function listingController($scope, blogContent){
var vm = this;
vm.articles = [];
grabData();
function grabData(){
return blogContent.getContent().then(function(data){
console.log(data.articles);
vm.articles = data.articles;
return vm.articles;
},function(err){
console.log(err);
vm.data = [];
});
}
}
})();
App.js:
(function(){
'use strict';
var dependencies = [
'ghpg',
'ngRoute'
];
angular.module('blogger', dependencies)
.config(Config);
Config.$inject = ['$locationProvider']
function Config($locationProvider){
$locationProvider.hashPrefix('!');
}
if (window.location.hash === '#_=_'){
window.location.hash = '#!';
}
//bootstrap angular
angular.element(document).ready(function(){
angular.bootstrap(document, ['ghpg']);
});
})();
LISTING VIEW:
<div class="container-fluid" data-ng-Controller="listingController as vm">
<h2> Listings </h2>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-8">
<div class="post-listing" data-ng-repeat="post in vm.articles">
<h3 class="article-title"><a target="_self" data-ng-href="/blog#/post/{{post.title}}"> {{ post.title }} </a></h3>
<div class="article-container">
<div class="article-date"><span class="article-date">{{ post.date }}</span></div>
<div class="article-post>"><span class="article-content"> {{ post.content }} </span></div>
</div>
</div>
</div>
</div>
</div>
Having trouble where I went wrong. I strongly suspect that it's some small typo or something with my SPA location/locationProvider in app.js but it looks the same in my other apps, unless my eyes are fooling me (which could be totally happening!)
What I did for a fix was simply this:
changed the listing view's anchor:
<h3 class="article-title"><a target="_self" data-ng-href="/post/{{post.title}}"> {{ post.title }} </a></h3>
to include the /blog# portion in the href so that I have:
<h3 class="article-title"><a target="_self" data-ng-href="/blog#/post/{{post.title}}"> {{ post.title }} </a></h3>
Simple fix, cause only the blog portion or webpage of my website is the angularJS, everything else is not so the routing was not being called to route it until it saw /blog# as part of the app.

Could not resolve '___' from state 'home' - angular ui-router issue

I'm new to angular and following this tutorial:
https://scotch.io/tutorials/angularjs-multi-step-form-using-ui-router
but i'm injecting this module into another existing module.
However, I keep getting a "could not resolve states" error - I'm not sure why but suspect its either a routes issue and I'm being dumb, or otherwise its a nested views issue (note nesting of ui-view in index.html, and again in home.html).
using angular ui version 0.2.13
angular version 1.3.14
Please help!!
Below is the relevant code:
structure:
home.html
<div id="form-container">
<div class="page-header text-center">
<h2>Let's Be Friends</h2>
<!-- the links to our nested states using relative paths -->
<!-- add the active class if the state matches our ui-sref -->
<div id="status-buttons" class="text-center">
<a ui-sref-active="active" ui-sref=".profile"><span>1</span> Profile</a>
<a ui-sref-active="active" ui-sref=".interests"><span>2</span> Interests</a>
<a ui-sref-active="active" ui-sref=".payment"><span>3</span> Payment</a>
</div>
</div>
<!-- use ng-submit to catch the form submission and use our Angular function -->
<form id="signup-form" ng-submit="processForm()">
<!-- our nested state views will be injected here -->
<div id="form-views" ui-view></div>
</form>
</div>
<!-- show our formData as it is being typed -->
<pre>
{{ formData }}
</pre>
index.html
<body> blah blah
<div ui-view></div>
<script src="app.js"></script>
<script src="javascripts/form.js"></script>
<script src="controllers/main.js"></script>
<script src="controllers/form-controller.js"></script>
</body
app.js
angular.module('MyApp', ['ngCookies','ngResource', 'ngMessages', 'mgcrea.ngStrap', 'formApp'])
.config(['$locationProvider', '$stateProvider', function($locationProvider, $stateProvider){
$locationProvider.html5Mode(true);
console.log($stateProvider);
}]);
form.js
angular.module('formApp', ['ngAnimate', 'ui.router'])
// configuring our routes
// =============================================================================
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show our basic form (/form)
.state('home', {
url: '/',
templateUrl: 'views/home.html',
controller: 'formController'
})
// nested states
// each of these sections will have their own view
// url will be nested (/form/profile)
.state('.profile', {
url: '/profile',
templateUrl: 'views/form-profile.html'
})
// url will be /form/interests
.state('.interests', {
url: '/interests',
templateUrl: 'views/form-interests.html'
})
// url will be /form/payment
.state('.payment', {
url: '/payment',
templateUrl: 'views/form-payment.html'
});
// catch all route
// send users to the form page
$urlRouterProvider.otherwise('/');
})
form-controller.js
// our controller for the form
// =============================================================================
angular.module('formApp')
.controller('formController', ['$scope', function($scope) {
// we will store all of our form data in this object
$scope.formData = {};
// function to process the form
$scope.processForm = function() {
alert('awesome!');
};
}]);
Your code is not following the tutorial exactly. Note that for child states to function, they must reference their parent state.
In the tutorial code:
.state('form.profile', {
In your code:
.state('.profile', {
If you change your child states to reference the parent, they will function correctly. i.e.
.state('home.profile', {

what does <!-- ngView : undefined --> mean

I get a dom like this:
<div class="row">
<::before>
<div class="col-lg-12">
<!-- ngView: undefined -->
<ng-view class="ng-scope">
<h1 class="ng-scope">Hello world</h1>
</ng-view>
</div>
<::after>
</div>
What does:
<!-- ngView: undefined -->
mean?
Everything seems to work fine, but I don't like this comment as it seems that something is not working properly?
The template look like this:
<h1>Hello world</h1>
and it is configured like this :
var myApp = angular.module('myApp', [
'ngRoute',
.....
]);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/my_template', {templateUrl: '/web-angular/my_template.html'})
.when( ..... );
}]);
Place your 'ng-view' directive in a div or span. Such as ...
<div ng-view></div>
<span ng-view></span>
Check out the IE restrictions here AngularJS IE Guide and take a look at number 3 and 4. From this, I take it that this is simply a warning. Something to catch your attention, and mine, just as it did. Note that declaring ng-view in your class will still work, but you will get the same warning message in your markup.
For anyone else coming across this and not having any luck with the other answer, I had this problem because I hadn't included the controller as a dependency of the module.
angular.module('myApp', ['module-for-missing-page'])
Including this dependency got the view loading correctly.
inject ur view in an anchor tag.Like this
<div>
Home
Students
Courses
<ng-view> </ng-view>
</div>
var app = angular.module("MyApp", ["ngRoute"])
.config(function ($routeProvider) {
$routeProvider
.when("/home", {
templateUrl: "Templates/home.html",
controller: "homeController"
})
.when("/courses", {
templateUrl: "Templates/courses.html",
controller: "courseController"
})
.when("/students", {
templateUrl: "Templates/students.html",
controller: "studentsController"
})
})
.controller("homeController", function ($scope) {
$scope.message = "I am in home controller";
})
.controller("courseController",function($scope){
$scope.message = "I am in courses controller";
})
.controller("studentsController", function ($scope) {
$scope.message = "I am in students controller";
})
and check whether u have put the correct ng-route links or not.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-route.min.js">
</script>

Resources