Here's my code:
controller.js
angular.module('myApp',['ui.router'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show all the polls
.state('polls', {
url: '/polls',
templateUrl: 'views/polls.html',
controller: 'pollsController'
})
// show new polls
.state('new', {
url: '/polls/add',
templateUrl: 'views/newPoll.html',
controller: 'newController'
});
$urlRouterProvider.otherwise('/polls');
})
.controller('pollsController', function($scope,$http) {
$http.get('/polls').then(function(data, status, headers, config) {
$scope.result = data;
}).catch(function(data) {
$scope.result = data;
});
})
.controller('newController',function($scope,$http) {
$http.get('/polls/add').then(function(data,status,headers,config) {
$scope.result = data;
}).catch(function(data) {
$scope.result = data;
});
});
index.html
<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<!-- <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/darkly/bootstrap.min.css"> -->
<link rel="stylesheet" type="text/css" href="views/css/style.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
<script type="text/javascript" src="controller.js"></script>
</head>
<body ng-app="myApp">
<div id="topheader">
<h1>myApp</h1>
</div>
<div class="topnav" id="topnavigation">
<a ui-sref-active="active" ui-sref="new">Add poll</a>
<a ui-sref-active="active" ui-sref="polls">All polls</a>
</div>
<div class="container">
<div ui-view></div>
</div>
</body>
</html>
polls.html
<div class="content">
<h2>View your polls!</h2>
<div class="allPolls" ng-repeat="item in result.data.polls">
<li> {{item.title}}
</li>
</div>
</div>
newPoll.html
<div class="content">
<form>
Title: <br><input type="text" name="title"><br>
Options (add line break between options): <br>
<textarea type="text" name="options">
</textarea>
<br>
<button type="button">Create new poll</button>
</form>
</div>
So now when I press the "Add poll"-button from the polls-page the page loads a page where is only the topnavigation-bar. When I press the "Add poll"-button again, the page loads the form from newPoll.html.
The url changes on the first click so everything should be working on the first click?
Related
Main page URL: http://localhost:3000/
Current second page URL: http://localhost:3000/#/titleDetails.html
Expected second page URL: http://localhost:3000/titleDetails.html
Currently when I click on the title in my main page, the URL contains an extra /# which causes the page to be redirected to titleDetails.html.
The directory of titleDetails.html and index.html is in the same directory.
May I know how can I fix this?
Original Post: AngularJS Display 1 Post in New Page
app.js
(function () {
angular
.module("BlogApp", [])
.config(function($locationProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
})
.controller("BlogController", BlogController);
function BlogController($scope, $http, $rootScope, $location) {
$scope.createPost = createPost;
$scope.deletePost = deletePost;
$scope.editPost = editPost;
$scope.updatePost = updatePost;
$scope.titleDetails = titleDetails;
$scope.postDetail = null;
function init() {
getAllPosts();
}
init();
function titleDetails(post)
{
$scope.postDetail = post;
$location.path('/titleDetails.html');
}
function updatePost(post){
console.log(post);
$http
.put("/api/blogpost/"+post._id, post)
.success(getAllPosts);
}
function editPost(postId){
$http
.get("/api/blogpost/"+postId)
.success(function(post){
$scope.post = post;
});
}
function deletePost(postId){
$http
.delete("/api/blogpost/"+postId)
.success(getAllPosts);
}
function getAllPosts(){
$http
.get("/api/blogpost")
.success(function(posts) {
$scope.posts = posts;
});
}
function createPost(post) {
console.log(post);
$http
.post("/api/blogpost",post)
.success(getAllPosts);
}
}
})();
index.html
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<input ng-model="post.title" class="form-control" placeholder="title"/>
<textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
<button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>
<button ng-click="updatePost(post)" class="btn btn-success btn-block">Update</button>
<div ng-repeat="post in posts">
<h2>
<a ng-click="titleDetails(post)">{{ post.title }} </a>
<a ng-click="editPost(post._id)" class="pull-right"><span class="glyphicon glyphicon-pencil"></span></a>
<a ng-click="deletePost(post._id)" class="pull-right"><span class = "glyphicon glyphicon-remove"></span></a>
</h2>
<em>{{post.posted}}</em>
<p>{{post.body}}</p>
</div>
</div>
</body>
</html>
titleDetails.html:
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<div>
<h2>
<a>{{ postDetail.title }} </a>
</h2>
<em>{{postDetail.posted}}</em>
<p>{{postDetail.body}}</p>
</div>
</div>
</body>
</html>
Console Error in index.html:
angular.js:13708 Error: [$location:nobase] http://errors.angularjs.org/1.5.7/$location/nobase
at angular.js:38
at sf.$get (angular.js:13384)
at Object.invoke (angular.js:4709)
at angular.js:4508
at d (angular.js:4655)
at e (angular.js:4679)
at Object.invoke (angular.js:4701)
at R.instance (angular.js:10234)
at m (angular.js:9147)
at g (angular.js:8510)
Angular has 3 routing operates:
Hashbang Mode
HTML5 Mode
Hashbang in HTML5 Mode
You can configure: $locationProvider.html5Mode(true).hashPrefix('!');
Check documentation
Expected Result: Opens up Title and Comment in titleDetails.html when Title is clicked in index.html.
Problem: URL changes to http://localhost:3000/titleDetails.html when Title is clicked.
But content remains the same. Page displays 0 post when I refreshed the URL.
Screenshot: (index.html) & (titleDetails.html after clicking a title in index.html)
Screenshot: (after refreshing titleDetails.html when content remains the same after redirecting from index.html)
Code:
1) index.html
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<base href="/" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<input ng-model="post.title" class="form-control" placeholder="title"/>
<textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
<button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>
<button ng-click="updatePost(post)" class="btn btn-success btn-block">Update</button>
<div ng-repeat="post in posts">
<h2>
<a ng-click="titleDetails(post)">{{ post.title }} </a>
<a ng-click="editPost(post._id)" class="pull-right"><span class="glyphicon glyphicon-pencil"></span></a>
<a ng-click="deletePost(post._id)" class="pull-right"><span class = "glyphicon glyphicon-remove"></span></a>
</h2>
<em>{{post.posted}}</em>
<p>{{post.body}}</p>
</div>
</div>
</body>
</html>
2) titleDetails.html
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<base href="/" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<div>
<h2>
<a>{{ postDetail.title }} </a>
</h2>
<em>{{postDetail.posted}}</em>
<p>{{postDetail.body}}</p>
</div>
</div>
</body>
</html>
3) app.js
(function () {
angular
.module("BlogApp", [])
.config(function($locationProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
})
.controller("BlogController", BlogController);
function BlogController($scope, $http, $rootScope, $location) {
$scope.createPost = createPost;
$scope.deletePost = deletePost;
$scope.editPost = editPost;
$scope.updatePost = updatePost;
$scope.titleDetails = titleDetails;
$scope.postDetail = null;
function init() {
getAllPosts();
}
init();
function titleDetails(post)
{
$scope.postDetail = post;
$location.path('/titleDetails.html');
}
function updatePost(post){
console.log(post);
$http
.put("/api/blogpost/"+post._id, post)
.success(getAllPosts);
}
function editPost(postId){
$http
.get("/api/blogpost/"+postId)
.success(function(post){
$scope.post = post;
});
}
function deletePost(postId){
$http
.delete("/api/blogpost/"+postId)
.success(getAllPosts);
}
function getAllPosts(){
$http
.get("/api/blogpost")
.success(function(posts) {
$scope.posts = posts;
});
}
function createPost(post) {
console.log(post);
$http
.post("/api/blogpost",post)
.success(getAllPosts);
}
}
})();
AngularJS is a SPA (single page application) oriented. Your links are still tied to the classic multiple page navigation. You will have to re-work your app since $location and $http.get are not the correct services for loading templates and navigation in your scenario.
AngularJS can load the template and update the address bar accordingly as long you use the $routeProvider. Scoth.io made a simple tutorial on how to setup routing.
But you basically have to include ngRoute to your application:
angular.module('ngRouteExample', ['ngRoute'])
Then configure your routes:
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'blogPosts.html',
controller: 'BlogController'
})
.when('/post/:id', {
templateUrl: 'titleDetails.html',
controller: 'TitleController'
});
}
Since the answer can get very long, the following Plunker demonstrates a simple routing implementation for you to learn:
https://plnkr.co/edit/twmbG0G9XjOqF82JtyMC?p=preview
I'm a newbie to Angular and working on a project but I'm having an issue with displaying info in two different pages.
I have a browse page that displays profiles
I also have a homepage where I want to display the contents of the browse page plus other miscellaneous information.
To do that I created a component(browsePage)
Then I added the component to the home.view.html
<browse-page></browse-page>
but the profiles don't show up.
In my browse page the profiles do show up.
My code:
app.config.js
$routeProvider
.when('/home', {
RouteData: {
bodyStyle: {
//'background': 'url(../images/bg-7.jpg)repeat'
'background-color': 'white'
}
},
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
.when('/browse', {
RouteData: {
bodyStyle: {
//'background': 'url(../images/bg-10.jpg)repeat'
'background-color': 'white'
}
},
controller: 'BrowseController',
templateUrl: 'browse/browse.view.html',
controllerAs: 'vm'
})
home.controller.js
angular.module("mango").controller("HomeController", HomeController);
function HomeController() {
}
angular.module('mango').controller('ExampleController', ['$cookies', function($cookies) {
}]);
home.view.html
This is the home page<br>
Miscellaneous info goes here
<browse-page></browse-page>
Miscellaneous info goes here<br>
end of home page
browse.component.js
console.log("In browse.component.js");
angular.module("mango").component("browsePage",{
templateUrl:"browse/browse.view.html",
controller:BrowseController
});
browse.controller.js
angular.module("mango").controller("BrowseController", BrowseController);
BrowseController.$inject = ["$rootScope","$location","AuthenticationService","$http"];
function BrowseController($rootScope, $location, AuthenticationService, $http){
var vm = this;
$http.get('browse_profiles.json').success(function(data){
vm.data = data;
console.log("data==>");
console.log(data);
});
}
browse.view.html
<br><br>
<!-- Page Content -->
<div class="container">
<!-- Jumbotron Header -->
<header class="jumbotron hero-spacer" >
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>
</header>
<hr>
<!-- Page Features -->
<div class="row text-center">
<img id="mySpinner" src="/images/loader.gif" ng-show="loading" />
{{alpine}}
<div class="col-md-3 col-sm-6 hero-feature" ng-repeat="profile in vm.data">
<div class="thumbnail">
<img src="{{profile.thumbnail}}" alt="">
<div class="caption">
<div class="username-status">
<span class="username pull-left"><a ng-href="#/profile/{{profile.username}}">{{profile.username}}</a></span>
<p ng-class-odd="'circle odd'" ng-class-even="'circle even'"></p>
</div>
</div>
</div>
</div>
</div>
<!-- /.row -->
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © Your Website 2014</p>
</div>
</div>
</footer>
</div>
End of browse view.
<br><br>
index.html
<!doctype html>
<html lang="en" ng-app="mango">
<head>
<meta charset="utf-8">
<title>Mango</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="css/style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="bower_components/angular-cookies/angular-cookies.js"></script>
<script src="app.config.js"></script>
<script src="login/route-data.js"></script>
<script src="navigation_menu/navigation_menu.config.js"></script>
<script src="browse/browse.controller.js"></script>
<script src="browse/browse.component.js"></script>
<script src="home/home.controller.js"></script>
<script src="profile/profile.controller.js"></script>
<script src="settings/settings.controller.js"></script>
<script src="login/login.controller.js"></script>
<script src="login/app-services/authentication.service.js"></script>
<script src="login/app-services/flash.service.js"></script>
<script src="login/app-services/user.service.local-storage.js"></script>
</head>
<body ng-style="RouteData.get('bodyStyle')" ng-cloak>
<navigationmenu ng-if="location.path() !== '/login'"></navigationmenu>
<ng-view autoscroll></ng-view>
</body>
</html>
I'm not getting any errors in the console.You can ignore the GET error.
What do I need to do to fix my problem?
I'm starting to think th
Thanks in advanced.
I think in your component, you haven't specified controllerAs, when you goto /browse, your browseView.html is getting the controller instance as vm, but when browseView.html is loaded through component,it is not getting the controller instance, as it is not getting instantiated like it is done, in routeProvider.
Try doing,
angular.module("mango").component("browsePage",{
templateUrl:"browse/browse.view.html",
controller:BrowseController,
controllerAs: 'vm'
});
Hope, this solves the issue.
When I visit my page, a get-request is fired 4 times, when It's just supposed to be fired 2 times. Take a look at the picture below:
Here is my code:
index.html:
<!DOCTYPE html>
<html ng-app="cryptlib">
<head>
<link href="css/style.css" rel="stylesheet" type="text/css">
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />
</head>
<body ng-controller="firstPageController">
<div ng-view>
</div>
</body>
<script src="js/angular-file-upload-shim.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script data-require="angular-route#*" data-semver="1.2.20" src="https://code.angularjs.org/1.2.20/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular-sanitize.js"></script>
<script src="js/angular-file-upload.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/directives.js"></script>
</html>
firstpage.html
<link href='http://fonts.googleapis.com/css?family=Fjord+One' rel='stylesheet' type='text/css'>
<div id="layout">
<div id="top">
<h2>CryptLib</h2>
</div>
<div id="main">
<div class="leftcontent">
<ul>
<li>>> Webbutveckling</li>
<li>>> Programmering</li>
<li>>> Elektronik</li>
<li>>> Vetenskap</li>
<li>>> Övrigt</li>
<li>>> Ladda upp</li>
</ul>
</div>
<div class="maincontent">
<li ng-repeat="book in books track by $index">
{{book}}
</li>
</div>
<div id="bottom">
<h3>Ladda upp {{selectedItem}}</h3>
<input type="text" ng-model="myModelObj">
Välj mapp:
<select ng-model="selectedItem" ng-options="item for item in items" ng-change="change()">
</select>
<input type="file" ng-file-select="onFileSelect($files)">
<!--Bild<input type="file" ng-file-select="onFileSelect($files)" multiple accept="image/*">-->
</div>
</div>
controller.js
angular.module('cryptlib_controllers')
.controller('firstPageController', ['$scope','$http','$location','$sce','$rootScope','$upload', function($scope, $http, $location, $sce, $rootScope, $upload) {
$http({
url: 'lib/actions.php',
method: 'GET',
params: {get_books: 1}
}).success(function(data) {
$scope.books = data;
});
$http({
url: 'lib/actions.php',
method: 'GET',
params: {get_dirs: 1}
});
console.log($scope.books);
$scope.onFileSelect = function($files) {
//Vi har valt en eller flea filer
//$files är en array innehållande de valda filerna att ladda upp. Dess namn, storlek och typ
for(var i = 0; i < $files.length; i++)
{
var file = $files[i];
$scope.upload = $upload.upload({
url: 'lib/actions.php',
data: {myObj: $scope.myModelObj},
file: file
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
console.log(data);
});
}
};
$scope.items = ['Programmering', 'Elektronik'];
$scope.change = function() {
alert($scope.selectedItem);
}
}]).controller('bookController', ['$scope','$http','$location','$sce','$rootScope','$upload', function($scope, $http, $location, $sce, $rootScope, $upload) {
}]);
Why is a get request fired 4times when I visit the page? It should only be fired 2times? Anyone who can explain?
Because you are defining firstPageController twice. First in the body tag, and then in the route.
I am working on my first website with AngularJS. My app works fine when I declare ng-app in the html tag. However, data binding stops working when I try to assign a name to the ng-app directive so that I can create a module with controllers and filters.
Here is my working code:
<!doctype html>
<html data-ng-app>
<head>
<meta charset="utf-8">
<title>Twittiment</title>
<link href="search_client.css" type="text/css" rel="stylesheet" />
<link href="tweet.css" type="text/css" rel="stylesheet" />
<script src="jquery.min.js"></script>
<script src="search_client.js"></script>
<script src="/js/highcharts.js"></script>
</head>
<body data-ng-controller="TweetCtrl">
<div id="main">
<div id="search_box">
<h1 id="title">Twitter Sentiment Analysis</h1>
<input name="search_terms" autofocus="autofocus" data-ng-model="query" />
<button id="search_button" data-ng-click="search()">Search</button>
<div id="data"></div>I can add:{{1+3}}</div>
<div id="search_results">Search tweets:
<input name="filter" data-ng-model="text" /><span>Displaying {{(tweets|filter:text).length}} of {{tweets.length}} tweets</span>
<div class="tweet" data-ng-repeat="tweet in tweets | filter:text">
<div class="tweet_left">
<div class="tweet_image"> <a href="https://twitter.com/{{tweet.user.screen_name}}">
<img src="{{tweet.user.profile_image_url}}">
</a>
</div>
</div>
<div class="tweet_right">
<div class="tweet_triangle"></div>
<div class="tweet_row">
<div class="tweet_username"> {{tweet.user.screen_name}}
<span class="tweet_name">{{tweet.user.name}}</span>
<span class="delete_tweet">Mark as irrelevant</span>
<input class="close_button" type="image" src="/xmark.jpg" alt="submit" ng-click="delete($index)">
</div>
</div>
<div class="tweet_row">
<div class="tweet_text">{{tweet.text}}</div>
</div>
<div class="tweet_row">
<div class="tweet_timestamp">
<img class="stream_bluebird" src="bird_16_blue.png"> <span class="retweets">{{tweet.retweet_count}} retweets</span>
{{tweet.created_at}}
<img src="reply.png" class="imageof_reply"> Reply
<img src="retweet.png" class="imageof_retweet"> Retweet
<img src="favorite.png" class="imageof_favorite"> Favorite
</div>
</div>
</div>
<div class="sentiment" data-ng-controller="RatingCtrl">
<div class="rating" data-ng-model="tweet.polarity">{{tweet.polarity}}</div>
<button data-ng-click="changeRating('Positive')">
<img class="positive" src="/thumbs-up-button.jpg">
</button>
<button data-ng-click="changeRating('Neutral')">
<img class="neutral" src="/thumbs-sideways-button.jpg">
</button>
<button data-ng-click="changeRating('Negative')">
<img class="negative" src="/thumbs-down-button.jpg">
</button>
</div>
</div>
</div>
</div>
<div class="total">
<h2 id="totalTitle"></h2>
<div>{{tweets.length}}</div>
<div id="totalPos"></div>
<div id="totalNeut"></div>
<div id="totalNeg"></div>
</div>
<div id="container" style="width:40%; height:400px;"></div>
<script src="/ang-Twittiment/app/lib/angular/angular.js"></script>
</body>
</html>
JS:
function TweetCtrl($scope, $http) {
$scope.search = function () {
$http({
method: 'GET',
url: 'http://localhost:8080/search_server.php?q=' + $scope.query
}).success(function (data) {
$scope.tweets = data;
})
.error(function (data) {
alert("search error")
});
};
$scope.delete = function (idx) {
$scope.tweets.splice(idx, 1);
};
}
function RatingCtrl($scope) {
$scope.changeRating = function (rating) {
$scope.tweet.polarity = rating;
}
}
And here is the code that doesn't work:
<html data-ng-app="myApp">
JS:
var myAppModule = angular.module('myApp', []);
myAppModule.controller('TweetCtrl', function ($scope, $http) {
$scope.search = function () {
$http({
method: 'GET',
url: 'http://localhost:8080/search_server.php?q=' + $scope.query
}).success(function (data) {
$scope.tweets = data;
})
.error(function (data) {
alert("search error")
});
};
$scope.delete = function (idx) {
var person_to_delete = $scope.tweets[idx];
$scope.tweets.splice(idx, 1);
};
});
myAppModule.controller('RatingCtrl', function ($scope) {
$scope.changeRating = function (rating) {
$scope.tweet.polarity = rating;
}
});
Can anyone tell me why data binding stops whenever I assign a name to the ng-app directive? Is there a step I'm missing when configuring the module? Any help would be greatly appreciated, please let me know if more information is needed.
actually you need to put your angular.js file reference before angular.module statement so it can identify angular otherwise when you will check the javascript error it shows angular is not define
var myAppModule = angular.module('myAppModule', []);
This should do it.
When you declare ng-app="myApp", angular compiler searches for controllers registered with "myApp", but the controllers are registered with "myAppModule"