I began following a tutorial to AngularJs today, but implementing something slightly different, now I'm stuck, seems that Angular is not recognizing the inline template "home".
P.S: To run this locally on chrome I had to install a webserver.
angular.module('little_tweet', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
})
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'PostsCtrl'
});
$urlRouterProvider.otherwise('home');
}])
.factory('posts', [function() {
var o = { posts: []};
return o;
}])
.controller('MainCtrl', ['$scope', 'posts', function($scope, posts){
$scope.posts = posts.posts;
$scope.current_user = 'me';
$scope.addPost = function() {
if(!$scope.message || $scope.message === '') { return; }
$scope.posts.push({
user: $scope.current_user,
message: $scope.message,
time: new Date()
});
$scope.message = '';
};
}])
.controller('PostsCtrl', ['$scope', '$stateParams', 'posts', function($scope, $stateParams, posts) {
$scope.post = posts.posts[$stateParams.id];
}]);
<html>
<head>
<title>Little Tweet</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="app.js"></script>
<style> .glyphicon-thumbs-up { cursor:pointer } </style>
</head>
<body ng-app="little_tweet">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
<div class="page-header">
<h1>Little Tweet</h1>
</div>
<div ng-repeat="post in posts">
<span style="font-size:20px; margin-left:10px;">
{{{post.user}}: {{post.message}} at {{post.time}}
</span>
</div>
<form ng-submit="addPost()"
style="margin-top:30px;">
<h3>Add a new post</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Message"
ng-model="message"></input>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</div>
</div>
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Little tweet</h1>
</div>
<!-- rest of template -->
</script>
</body>
</html>
Remove the / from template url in routes.
EDIT
there is an extra { in {{{post.user}}: {{post.message}} at {{post.time}}.
Related
I am trying to access an http get response called during route change using ui route. The resolve itself happens but i am unable to access the response. I have tried some approaches in "listcontroller" which is shown. I am using a sample httpget url found in the internet for test. Angular version: v1.2.32. ui-route: 1.0.15.
script.js
var app = angular.module("Rasp", ["ui.router"])
.config(['$stateProvider', '$urlRouterProvider',function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state("ipList", {
url: "/ipList",
templateUrl: "templates/list.html",
controller: "listController",
resolve: {
SensorIP : function($http){
$http.get('https://httpbin.org/ip')
.then(function(response){
console.log('res');
console.log(response);
return response.data.origin;
});
}
}
})
.state("home", {
url: "/home",
templateUrl: "templates/home.html",
controller: "homeController"
});
}])
.controller("RaspController", ['$scope', '$http', function ($scope, $http) {
$scope.getDetails = function () {
// $http.get('https://httpbin.org/ip')
// .then(function (response) {
// console.log(response);
// $scope.response = response;
// },
// function (error) { console.log(error); }
// );
// };
}])
.controller("homeController", ['$scope', function ($scope) {
}])
.controller("listController", ['$scope','SensorIP',function ($scope,SensorIP) {
$scope.sensorList = SensorIP;
var vm = this;
this.list1 = SensorIP;
var logfunc = function() {console.log($scope.sensorlist)};
}])
list.html
<div>
{{list1}}
{{sensorlist}}
<button class="btn btn-danger navbar-btn" ng-click="logfunc()">click</button>
</div>
home.html
<h4>Click on "Get IP List" to get the list of IPs</h4>
<a ui-sref="ipList"><button id="button" >Get IP List</button></a>
index.html
<!DOCTYPE html>
<head>
<title>Title(To be changed)</title>
<!--JS-->
<script type="text/javascript" src="../node_modules/angular/angular.js"></script>
<script type="text/javascript" src="../node_modules/#uirouter/angularjs/release/angular-ui-router.js"></script>
<script type="text/javascript" src="script.js"></script>
<!-- -->
<!--CSS-->
<link rel="stylesheet" href="../css/style.css">
<!-- -->
</head>
<body>
<div ng-app="Rasp">
<div ng-controller="RaspController">
<div class="sidenav">
<!--
<a ui-sref="home" id="dot-button"><button class="btn btn-danger navbar-btn" >Home</button></a>
<a ui-sref="ipList" id="dot-button"><button class="btn btn-danger navbar-btn" >IP List</button></a>
-->
<a ui-sref="home">home</a>
<a ui-sref="ipList" >ipList</a>
</div>
<div>
<ui-view id="uiview"></ui-view>
</div>
</div>
</div>
</body>
I'm new to AngularJS and I tried creating a sample login page and I tried routing to other page on successful login but nothing shows up in ng-view and my code has no error. What could be the problem?
index.html
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
route.js"></script>
<script src="maincontroller.js"></script>
</head>
<body>
<div ng-view>
</div>
</body>
</html>
controller
var app = angular.module('myapp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'login.html',
controller: 'maincontroller'
})
.when('/dashboard', {
templateUrl: 'dashboard.html'
})
.otherwise('/', {
templateUrl: '/'
})
});
app.controller('maincontroller', function($scope, $location) {
$scope.submit = function($scope) {
var username = $scope.username;
var password = $scope.password;
if ($scope.username == 'ashok' && $scope.password == 'ashok') {
$location.path('/dashboard');
} else {
windows.alert('wrong stuff');
}
};
});
login.html
<div ng-controller="maincontrol">
<form action="/" name="formgroup">
<label>Username:<input type="text" id="username" ng-model="username"/></label><br>
<label>Password:<input type="password" id="password" ng-model="password"/></label><br>
<button type="button" ng-click="submit()">Login</button>
</form>
You should mention ng-app in your HTML to make this an Angular app.
<html ng-app='myapp'>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
route.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-view>
</div>
</body>
</html>
Maincontroller.js
var app = angular.module('myapp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'login.html',
controller: 'maincontroller'
})
.when('/dashboard', {
templateUrl: 'dashboard.html'
})
.otherwise('/', {
templateUrl: '/'
})
});
app.controller('maincontroller', function($scope, $location) {
$scope.submit = function() {
var username = $scope.username;
var password = $scope.password;
if ($scope.username == 'ashok' && $scope.password == 'ashok') {
$location.path('/dashboard');
} else {
windows.alert('wrong stuff');
}
};
});
$scope is already injected in to the controller and you are passing that as a parameter to your submit function which is undefined since you did not pass anything on submit.
Login.html
<form action="/" name="formgroup">
<label>Username:<input type="text" id="username" ng-model="username"/></label><br>
<label>Password:<input type="password" id="password" ng-model="password"/></label><br>
<button type="button" ng-click="submit()">Login</button>
</form>
Since you are injecting controller on routing, You don't have to use ng-controller in your login.html. It makes the controller execute again.
Check this Plunker: https://plnkr.co/edit/8jPJ7WOa3ixjqeRU8bpg?p=preview
I will recomment to use ng-app in body .
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
route.js"></script>
<script src="maincontroller.js"></script>
</head>
<body ng-app="myapp">
<div ng-view>
</div>
</body>
</html>
also User maincontroller in login page
<div ng-controller="maincontroller">
<form action="/" name="formgroup">
<label>Username:<input type="text" id="username" ng-model="username"/></label><br>
<label>Password:<input type="password" id="password" ng-model="password"/></label><br>
<button type="button" ng-click="submit()">Login</button>
</form>
</div>
not sure what I have wrong here but the data doesn't display with this code and the only error I get is an XML Reading error XML in booksincategory.html , any ideas? Thanks
**booksincategory.html **
<div class="category col" ng-repeat="book in detail">
<h3 class="title">{{book.title}}</h3>
</div>
controller
app.controller('BookCategoryController', ['$scope', 'bookcategories', '$routeParams', function($scope, bookcategories, $routeParams) {
bookcategories.getAllBooks($scope.id).then(function(response) {
$scope.detail = response.data.books[$routeParams.categoryId];
});
}]);
service
app.service('bookcategories', ['$http', function($http) {
return {
getAllBooks: function(id) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/'+ id + '/books.json')
}
}
}]);
app.js
var app = angular.module('ReaderApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
.otherwise({
redirectTo: '/books'
});
});
index.html
<div class="main">
<div class="container">
<div ng-view></div>
</div>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/BookCategoryController.js"></script>
<!-- Services -->
<script src="js/services/bookcategories.js"></script>
I'm new to AngularJs and am stuck on a tutorial in the Routing section: https://thinkster.io/tutorials/mean-stack/routing-views-with-angular
Error Message:
Uncaught Error: [$injector:modulerr] Failed to instantiate module flapperNews due to:
Error: [$injector:nomod] Module 'flapperNews' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Prior to this error message I had a later version of angularjs (1.5.7) and it gave me this error - someone suggested online that you change the version. I had this error then:
Uncaught Error: [$injector:modulerr]
Please help me so that I can move on and get back to learning.
Here are my files:
index.html:
<html>
<head>
<title>My Angular App!</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="app.js"></script>
<style> .glyphicon-thumbs-up { cursor:pointer } </style>
</head>
<body ng-app="flapperNews">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Flapper News</h1>
</div>
<!-- rest of template -->
<div ng-repeat="post in posts | orderBy:'-upvotes'">
<span ng-click="incrementUpvotes(post)">▲</span>
<span ng-click="decrementUpvotes(post)">▼</span>
<span style="font-size:20px; margin-left:10px;">
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</span>
- upvotes: {{post.upvotes}}
</div>
<form ng-submit="addPost()"
style="margin-top:30px;">
<h3>Add a new post</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Title"
ng-model="title"></input>
</div>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Link"
ng-model="link"></input>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</script>
</body>
</html>
app.js:
var count = 0;
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
count++;
return Math.floor(Math.random() * (max - min)) + min;
}
(function (){
angular.module('flapperNews', ['ui.router'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home');
}
])
.factory('posts', [function(){
// service body
var obj = {
posts: []
};
return obj;
}])
.controller('MainCtrl',[
'$scope',
'posts',
function($scope, posts){
$scope.test = 'Reddit Emulator';
$scope.posts = posts.posts
$scope.addPost = function(){
if ($scope.title === '' || $scope.title == null)
$scope.title = 'post ' + (count + 1);
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: getRandomInt(0,25)
});
$scope.posts = posts.posts
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
};
$scope.decrementUpvotes = function(post) {
post.upvotes -= 1;
};
}]);
})
THanks!
Top of my files seem to have gotten cut off but I don't have time to fix it ATM. Sorry
Your Javascript code encapsulated between
(function (){
...
})
needs to be executed in order to load the code inside. For that, You can add (); at the end
(function (){
...
})();
Your app.js is malformed.
Try this
angular.module('flapperNews', ['ui.router'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home');
}
])
.factory('posts', [function(){
// service body
var obj = {
posts: []
};
return obj;
}])
.controller('MainCtrl',[
'$scope',
'posts',
function($scope, posts){
$scope.test = 'Reddit Emulator';
$scope.posts = posts.posts
$scope.addPost = function(){
if ($scope.title === '' || $scope.title == null)
$scope.title = 'post ' + (count + 1);
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: getRandomInt(0,25)
});
$scope.posts = posts.posts
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
};
$scope.decrementUpvotes = function(post) {
post.upvotes -= 1;
};
}]);
Then put the getRandomInt function inside the controller.
I am new to angularjs ,i make a sample app with custom directives now i add routing as well but it doesn't working.When i start project nothing is displayed in browser.
here is my index.html:
<html ng-app="myApp">
<head>
<title>Reddit New World News (Task)</title>
<link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<script src="angular/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="myApp.js"></script>
<script src="myAppCtrl.js"></script>
<script src="routes.js"></script>
<script src="headerDirective.js"></script>
<script src="searchDirective.js"></script>
<script src="myDataDirective.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
myAppCtrl:
// TODO: Wrap in anonymous function
(function () {
var myApp = angular.module('myApp', ['ui.router']);
// TODO: min-safe with bracket notation
myApp.controller('myAppCtrl', ['$scope', '$http', function($scope, $http) {
$scope.sortType = '';
$scope.sortReverse = true;
// TODO: Keep lines short - it's easier to read
$http.get("https://www.reddit.com/r/worldnews/new.json")
.success(function (response) {
$scope.stories = response.data.children;
});
}]);
myApp.controller('aboutController',function(){
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
myApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
})();
headerDirective.html:
<div class="top-header"></div>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="header">
<h1>Reddit</h1>
</div>
<div class="header-right">
<h2>World's Latest News</h2>
</div>
<div>
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
</nav>
<div class="clearfix"></div>
</div>
routes.js:
angular.module('myAppCtrl')
.config(['$stateProvider', '$locationProvider', '$urlRouterProvider',
function ($stateProvider, $locationProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/index.html');
// See route.webapp.js for allowed routes
$stateProvider
.state('app', {
templateUrl: '/templates/app.html',
controller: 'myAppCtrl',
abstract: true
})
.state('app.home', {
url: '/home',
templateUrl: '/templates/index.html',
controller: 'myAppCtrl'
})
.state('app.about', {
url: '/about',
templateUrl: '/templates/about.html',
controller: 'aboutController'
})
.state('app.contact', {
url: '/contact',
templateUrl: '/templates/contact.html',
controller: 'contcatController'
});
$locationProvider.html5Mode(true);
}
]);
})();
any guide thanks.
First there is a problem with your config block :
myApp.config(...)
not
angular.module('myAppCtrl').config(...);
Else you're redeclaring a new module. That doesn't make sense. You mix up controllers and module, that's two different things.
Then you have to change some things in your HTML file :
If you're using UI-Router it's :
<div ui-view></div>
not like ngRouter :
<div ng-view></div>
Then you're using $locationProvider.html5Mode(true);
So you have to configure your server to emulate paging, see doc.
Finally you have to add the base href of your angular application in the <head> tag like that :
<base href="/">