Angular routing/path change and scope issues - angularjs

I am new to AngularJS and I'm facing these issues :
I want to have a list of items (movies) and when I click on the image or on the title I want the path to be like #/movie/id. For that I tried using ngRoute and also tried path but I have faced errors in both, can you guide me which one is suitable for my case and how can I use it?
As you can see in the HTML code, I am trying to draw a search box but right now when the API runs and returns data the whole content of the ng-app is being replaced with the movie list, should I create a new scope for just the content I want to change, if so how and where?
Here is my code:
var movies = angular.module("movies", []);
movies.controller('movieController', function ($scope, $http) {
$http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json', {
params: {
limit : 16,
country : 'us',
apikey: 'rssd8z7pfw5t4nyd3cpszzzm',
callback: 'JSON_CALLBACK'
}
})
.success(function (data) {
$scope.movies = data.movies;
});
});
//added ngroute
var app = angular.module('movies', ['ngRoute']);
app.config(
function($routeProvider) {
$routeProvider.
when('/', {templateUrl:'/'}).
when('/movie/:id',
{
controller:UserView,
templateUrl: function(params){ return '/moviessssssss/' + params.id; }
}
).
otherwise({redirectTo:'/'});
}
);
app.controller('UserView', function($scope) {
$scope.movies = 'hereeeeeee!';
});
<html ng-app="movies">
<head>
<link rel="stylesheet" hrf="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>
<body>
<div class="ng-scope">
Search : <input type="text" placeholder="filter for..." >
</div>
<div ng-view>
{{ message }}
<table ng-controller="movieController" class="ng-cloak">
<tr ng-repeat="movie in movies">
<td><a ng-href="#movie" ><img ng-src="{{ movie.posters.thumbnail}}"/></a></td>
<td><a ng-href="#movie" > {{ movie.title }} </a></td>
</tr>
</table>
</div>

For getting the links:
ng-href="{{'/#/movie/'+movie.id}}"
Then for getting the filter to work,
Put ng-model to your search box. And in your ng-repeat add | filter: ng-modelname
var movies = angular.module("movies", []);
movies.controller('movieController', function ($scope, $http) {
$http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json', {
params: {
limit : 16,
country : 'us',
apikey: 'rssd8z7pfw5t4nyd3cpszzzm',
callback: 'JSON_CALLBACK'
}
})
.success(function (data) {
$scope.movies = data.movies;
console.log($scope.movies);
});
});
<html ng-app="movies">
<head>
<link rel="stylesheet" hrf="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>
<body>
<div class="ng-scope">
Search : <input type="text" placeholder="filter for..." ng-model="search">
</div>
<div ng-view>
{{ message }}
<table ng-controller="movieController" class="ng-cloak">
<tr ng-repeat="movie in movies | filter:search">
<td><a ng-href="{{'/#/movie/'+movie.id}}" ><img ng-src="{{ movie.posters.thumbnail}}"/></a></td>
<td><a ng-href="{{'/#/movie/'+movie.id}}" > {{ movie.title }} </a></td>
</tr>
</table>
</div>

TL;DR
Click Here to see a live plunker example.
in my example, i used bootstrap. remove if irrelevant
there is a TODO in my plunker - the server side movie filtering (when you type a something in the search field). you need to read more about it in developer.rottentomatoes.com
This is the routing configuration i would define:
movies.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/movies', {
templateUrl: 'movies.html',
controller: 'MoviesController',
resolve: {
movies: function($http) {
return $http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json', {
params: {
limit: 16,
country: 'us',
apikey: 'rssd8z7pfw5t4nyd3cpszzzm',
callback: 'JSON_CALLBACK'
}
});
}
}
})
.when('/movies/:id', {
templateUrl: 'movie.html',
controller: 'MovieController',
resolve: {
movie: function($http, $route) {
var id = $route.current.params.id;
return $http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/movies/' + id + '.json', {
params: {
limit: 1,
country: 'us',
apikey: 'rssd8z7pfw5t4nyd3cpszzzm',
callback: 'JSON_CALLBACK',
q: id
}
});
}
}
})
.otherwise({
redirectTo: '/movies'
});
});
/movies - a list of all movies
/movies/<movie id> - a specific details about the movie
NOTE - i used resolve to pre-fetch the json data (this is optional)
index.html
this is the main html code of your
<!DOCTYPE html>
<html ng-app="movies">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="app.js"></script>
</head>
<body>
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
movies.html
the view of the movie list.
we get the specific movie redirect by <a ng-href="#/movies/{{movie.id}}">
<input class="form-control" type="text" placeholder="Search ..." ng-model="search" >
<hr>
<table>
<tr ng-repeat="movie in movies | filter:search">
<td><a ng-href="#/movies/{{movie.id}}" ><img ng-src="{{ movie.posters.thumbnail}}"/></a></td>
<td><a ng-href="#/movies/{{movie.id}}"> {{ movie.title }} </a></td>
</tr>
</table>
movie.html
the view of the specific movie
<img class="img-responsive" ng-src="{{ movie.posters.detailed}}"/>
<h3>{{movie.title}} <small>{{movie.year}}</small></h3>
<p>{{movie.synopsis}}</p>
<hr>
<a class="btn btn-default" href="#/movies">Back</a>
<hr>
<pre>{{movie | json}}</pre>
MoviesController
the controller attached to the movies.html view
the $scope.$watch('search', is required to query the server for each input change you make. it's currently not working properly; rottentomatoes.com ignoring the q param. you need to read more about it in developer.rottentomatoes.com
movies.controller('MoviesController', function($scope, $http, movies) {
$scope.search = '';
$scope.$watch('search', function(newValue) {
// TODO: you need to request again the movie list from the server.
// Read more about the API here:
// http://developer.rottentomatoes.com/docs/read/json/v10/Movies_Search
$http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json', {
params: {
limit: 16,
country: 'us',
apikey: 'rssd8z7pfw5t4nyd3cpszzzm',
callback: 'JSON_CALLBACK',
q: newValue
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
console.log(data);
$scope.movies = data.movies;
});
});
$scope.movies = movies.data.movies;
});
MovieController
the controller attached to the movie.html view
movies.controller('MovieController', function($scope, movie) {
$scope.movie = movie.data;
});
Live example - http://plnkr.co/edit/cJXTZWqBUXNTPinf7AoV?p=preview

For your first question do this:
<td><a ng-href="#/movie/{{movie.id}}"> {{movie.title}} </a></td>

Related

Populate a combobox in Angular with Java BackEnd

The thing is as told in the title.
(function(){
var app = angular.module('sbi', [ ]);
app.controller('PanelController', function (){
this.tab = 1;
this.selectTab = function (setTab){
this.tab = setTab;
};
this.isSelected = function(checkTab) {
return this.tab === checkTab;
};
});
app.controller('MyCtrl', function($scope, $compile) {
'use strict';
$scope.data = { "name": ""};
$scope.reset = function() {
$scope.data.name = "";
$scope.data.codeSub = "";
$scope.data.cognSub = "";
$scope.data.codfis = "";
$scope.data.drpdownvalue = "";
$scope.form.$setPristine();
}
});
app.controller('DdController', function($scope, $compile) {
'use strict';
var loadUrl = contextName+"/subinstaller/inserimento/dettaglio.do?methodName=doListenerStato";
$.ajax({
async: false,
url : loadUrl,
type: "GET",
data: data,
dataType: 'json',
cache: false,
complete: function(){
_show_(false,'waitPanel');
},
success : function (data, stato) {
$('#service').empty()
for(var i = 0; i < data.length; i++) {
$("#service").append($('<option value="'+data[i].code+'">'+data[i].descr+'</option>'));
}
$('#service').trigger("chosen:updated");
},
error : function (richiesta, stato, errori) {
_show_(false,'waitPanel');
alert("error caricaServices");
}
});
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script><!DOCTYPE html>
<html ng-app="sbi">
<head>
<link href="utils/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<style>
table, td { border-width: 2px; border-collapse: collapse; padding: 15px; color: #000000; text-align: center; }
table.pos_fixed1 { position:relative; top:30px; left:10px; }
</style>
</head>
<body>
<form name="form">
<div data-ng-controller="MyCtrl">
<table summary="" width="10%" class="pos_fixed1" align="center">
<tr><td>Code Subinstaller<br><input type="text" ng-model="data.codeSub" /></td>
<td>Stato<br>
<select ng-model="data.drpdownvalue">
<option value=""> -- Seleziona -- </option>
</select> </td><td></td></tr>
<tr><td>Nome Sub Installer<input type="text" ng-model="data.name" /></td>
<td>Cognome Sub Installer<input type="text" ng-model="data.cognSub" /></td>
<td>Codice Fiscale<input type="text" ng-model="data.codfis" /></td></tr>
</table><br><br>
</form>
<section>
<div class="text-center">
<form name="form" id="form" novalidate>
<div>
<button class="btn-xs" data-ng-click="">Cerca</button>
<button class="btn-xs" ng-click="reset()">Pulisci</button>
</div>
</div>
</form>
</div>
</section>
<section ng-controller="PanelController as panel">
<ul class="nav nav-pills" >
<li ng-class="{ active:panel.isSelected(1) }"> <a href ng-click="panel.selectTab(1)">Risultati</a></li>
<li ng-class="{ active:panel.isSelected(2) }"> <a href ng-click="panel.selectTab(2)">Dettaglio</a></li>
</ul>
<div class="panel" ng-show="panel.isSelected(1)">
<h4>Risultati</h4>
<p> :))) </p>
</div>
<div class="panel" ng-show="panel.isSelected(2)">
<h4>Dettaglio</h4>
<p> Not skilled enough yet</p>
</div>
</section>
<script type="text/javascript" src="utils/angular.min.js"></script>
<script type="text/javascript" src="controllers/sbi_inserimento_controller1.js"></script>
</body>
</html>
The function "DoListenerStato" has its query and it works (tried in Java)
But the combobox is not being populated.
Have I used ajax correctly? If so, what can I do?
I'd prefer to keep using ajax for this work, if possible.
Can you try $http.get instead of $.ajax.
in Controller.js file:
$scope.data = {};
$http.get(loadUrl).then(function (response){
$scope.data = response.data;
//success callback
}, function (response) {
//error callback
});
Since you already have data.**** in your ng-model this should solve it.

AngularJS Wire up a Backend c/p from site not working

i'm trying to get this example working in Visual Studio 2015. I've created empty project and c/p files from site and for some reason i'm getting following error:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.3/$injector/modulerr?p0=project&p1=Error%3A…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.3%2Fangular.min.js%3A39%3A135)
I've googled a bit around and saw similar problems with version 1.2.x, suggested fix is not working. What am i missing?
project.js
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://ng-projects-list.firebaseio.com/')
.service('fbRef', function(fbURL) {
return new Firebase(fbURL)
})
.service('fbAuth', function($q, $firebase, $firebaseAuth, fbRef) {
var auth;
return function () {
if (auth) return $q.when(auth);
var authObj = $firebaseAuth(fbRef);
if (authObj.$getAuth()) {
return $q.when(auth = authObj.$getAuth());
}
var deferred = $q.defer();
authObj.$authAnonymously().then(function(authData) {
auth = authData;
deferred.resolve(authData);
});
return deferred.promise;
}
})
.service('Projects', function($q, $firebase, fbRef, fbAuth, projectListValue) {
var self = this;
this.fetch = function () {
if (this.projects) return $q.when(this.projects);
return fbAuth().then(function(auth) {
var deferred = $q.defer();
var ref = fbRef.child('projects-fresh/' + auth.auth.uid);
var $projects = $firebase(ref);
ref.on('value', function(snapshot) {
if (snapshot.val() === null) {
$projects.$set(projectListValue);
}
self.projects = $projects.$asArray();
deferred.resolve(self.projects);
});
//Remove projects list when no longer needed.
ref.onDisconnect().remove();
return deferred.promise;
});
};
})
.config(function($routeProvider) {
var resolveProjects = {
projects: function (Projects) {
return Projects.fetch();
}
};
$routeProvider
.when('/', {
controller:'ProjectListController as projectList',
templateUrl:'list.html',
resolve: resolveProjects
})
.when('/edit/:projectId', {
controller:'EditProjectController as editProject',
templateUrl:'detail.html',
resolve: resolveProjects
})
.when('/new', {
controller:'NewProjectController as editProject',
templateUrl:'detail.html',
resolve: resolveProjects
})
.otherwise({
redirectTo:'/'
});
})
.controller('ProjectListController', function(projects) {
var projectList = this;
projectList.projects = projects;
})
.controller('NewProjectController', function($location, projects) {
var editProject = this;
editProject.save = function() {
projects.$add(editProject.project).then(function(data) {
$location.path('/');
});
};
})
.controller('EditProjectController',
function($location, $routeParams, projects) {
var editProject = this;
var projectId = $routeParams.projectId,
projectIndex;
editProject.projects = projects;
projectIndex = editProject.projects.$indexFor(projectId);
editProject.project = editProject.projects[projectIndex];
editProject.destroy = function() {
editProject.projects.$remove(editProject.project).then(function(data) {
$location.path('/');
});
};
editProject.save = function() {
editProject.projects.$save(editProject.project).then(function(data) {
$location.path('/');
});
};
});
index.html
<!doctype html>
<html ng-app="project">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-resource.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.9.0/angularfire.min.js"></script>
<script src="project.js"></script>
</head>
<body>
<h2>JavaScript Projects</h2>
<div ng-view></div>
</body>
</html>
list.html
<input type="text" ng-model="projectList.search" class="search-query" id="projects_search"
placeholder="Search">
<table>
<thead>
<tr>
<th>Project</th>
<th>Description</th>
<th><i class="icon-plus-sign"></i></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="project in projectList.projects | filter:projectList.search | orderBy:'name'">
<td><a ng-href="{{project.site}}" target="_blank">{{project.name}}</a></td>
<td>{{project.description}}</td>
<td>
<a ng-href="#/edit/{{project.$id}}"><i class="icon-pencil"></i></a>
</td>
</tr>
</tbody>
</table>
detail.html
<form name="myForm">
<div class="control-group" ng-class="{error: myForm.name.$invalid && !myForm.name.$pristine}">
<label>Name</label>
<input type="text" name="name" ng-model="editProject.project.name" required>
<span ng-show="myForm.name.$error.required && !myForm.name.$pristine" class="help-inline">
Required {{myForm.name.$pristine}}
</span>
</div>
<div class="control-group" ng-class="{error: myForm.site.$invalid && !myForm.site.$pristine}">
<label>Website</label>
<input type="url" name="site" ng-model="editProject.project.site" required>
<span ng-show="myForm.site.$error.required && !myForm.site.$pristine" class="help-inline">
Required
</span>
<span ng-show="myForm.site.$error.url" class="help-inline">
Not a URL
</span>
</div>
<label>Description</label>
<textarea name="description" ng-model="editProject.project.description"></textarea>
<br>
Cancel
<button ng-click="editProject.save()" ng-disabled="myForm.$invalid"
class="btn btn-primary">
Save
</button>
<button ng-click="editProject.destroy()"
ng-show="editProject.project.$id" class="btn btn-danger">
Delete
</button>
</form>
Project tree
Can anyone point me in the right direction. Thanks
You are trying to inject projectListValue service which is not defined for your module named project.

Syncronization with angularjs $http function

I am new to angularjs and I have a very small app that loads contacts from my server. The code snippet here is the complete app.js.
The problem is that I can't figure out how to do the server call with sync. In the code snippet, when I refresh the page, alert 3 is displayed, then alert 2, and then finally alert 4. The function is immediately returning since the server http call take some time to do. So what I get in the browser is a display of the 2 test item in the array "contacts". Alert 4 finally comes along, but it is too late. Any help would be appreciated.
var module = angular.module('app', []);
module.service('ContactService', function ($http) {
//contacts array to hold list of all contacts - 2 entries for test
//var $contacts = [];
var contacts = [
{
id: 0,
'First_Name': 'Harmon',
'Last_Name': 'Adams',
'Home_Phone': '123-2343-44'
},
{
id: 1,
'First_Name': 'Sam',
'Last_Name': 'Spade',
'Home_Phone': '123-2343-44'
}
];
// returns the contacts list
this.list = function () {
// var contacts = [];
$http.post('http://localhost/Contacts7/GetData.php', {'cat' : 'Friends'}).
success(function(data) {
contacts = data.datarecords;
alert('4 - within $post - '+contacts);
}).
error(function(data, status){
alert('error!');
});
alert('3 - before return - '+contacts);
return contacts;
}
});
module.controller('ContactController', function ($scope, ContactService ) {
$scope.contacts = ContactService.list();
alert('2 - after list - '+ $scope.contacts);
});
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Contact Dialer </title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div ng-app="app" ng-controller="ContactController">
<div class="container" >
<div class="row row-centered">
<div class="col-md-2 button-row col-centered">
<button type="button" class="btn btn-Primary btn-l btn-block" ng-click="GetByCat('Favorites')">Favorites</button>
</div>
<div class="col-md-2 button-row col-centered">
<button type="button" class="btn btn-Primary btn-l btn-block" ng-click="GetByCat('Friends')">Friends</button>
</div>
<div class="col-md-2 button-row col-centered">
<button type="button" class="btn btn-Primary btn-l btn-block" ng-click="GetByCat('Loose Friends')">Loose Friends</button>
</div>
<div class="col-md-2 button-row col-centered">
<button type="button" class="btn btn-Primary btn-l btn-block" ng-click="GetByCat('Loose_Loose Friends')">Loose-Loose Friends</button>
</div>
<div class="col-md-2 button-row col-centered">
<button type="button" class="btn btn-Primary btn-l btn-block" ng-click="GetByCat('Business')">Business</button>
</div>
<div class="col-md-2 button-row">
</div>
</div>
{{xxx}}
<table class='table table-striped table-bordered'>
<th class = 'text-center'>Name</th>
<th class = 'text-center'>Home Phone</th>
<th class = 'text-center'>Mobile Phone</th>
<th class = 'text-center'>Bus. Phone</th>
</tr>
<tr ng-repeat='contact in contacts'>
<th class = 'text-center' >{{contact.Last_Name}}, {{contact.First_Name}}</th>
<td class = 'text-center'>{{contact.Home_Phone}}</td>
<td class = 'text-center'>{{contact.Mobile_Phone}}</td>
<td class = 'text-center'>{{contact.Business_Phone}}</td>
</tr>
</table></div>
</div>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/underscore-min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/app.js"></script>
</body>
</h
You can't return contacts from your service because contacts is going to be determined asynchronously. Instead you need to return a promise for the contacts, which you can use to populate your controller's contacts when they are done being retrieved.
Service:
module.service('ContactService', ['$http', function ($http) {
return {
list: function () {
return $http.post('http://localhost/Contacts7/GetData.php',
{'cat' : 'Friends'})
.then(function (response) {
return response.data.datarecords;
})
.catch(function (error) {
throw new Error("Failed to retrieve contacts!");
});
}
};
}]);
Note You may have noticed that I changed the first line from using the magic dependency injection style to using the array-style dependency injection. This is just my personal preference (because I consider the magic DI style to be a bad idea), and not something that you have to do. The same applies to the code below.
Controller:
module.controller('ContactController', ['$scope', 'ContactService',
function ($scope, ContactService ) {
$scope.contacts = [];
ContactService.list()
.then(function (contacts) {
$scope.contacts = contacts;
alert('2 - after list - '+ $scope.contacts);
});
}]);
Don't return contacts object from outside ajax.
It should be return contacts object from its success callback.
// returns the contacts list
this.list = function () {
// var contacts = [];
$http.post('http://localhost/Contacts7/GetData.php', {'cat' : 'Friends'}).then(
//success call back
function(data) {
contacts = data.datarecords;
alert('4 - within $post - '+contacts);
return contacts;
},
//error call back
function(data, status){
//error handling can be done here
alert('error!');
return;
});
Hope this may help full to you.

AngularJS routing not working after adding second state

I am using the ui.router. First when I just set the home state everything was working fine. But after adding the articles state my routing wouldn't work. I have following angular code:
var app = angular.module('ibrahimsBlog', ['ui.router'])
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'PrimaryController'
});
.state('articles', {
url: '/articles/{id}',
templateUrl: '/articles.html',
controller: 'ArticlesController'
});
$urlRouterProvider.otherwise('home');
}])
app.factory('articlesFactory', [function(){
var art = { articles: [] };
return art;
}])
app.controller('ArticlesController', [
'$scope',
'$stateParams',
'articlesFactory',
function($scope, $stateParams, articlesFactory){
$scope.article = articlesFactory.articles[$stateParams.id];
}]);
app.controller('PrimaryController', [
// Two Way Data Binding ist nur möglich mit scope Variablen.
'$scope',
'articlesFactory',
function($scope, articlesFactory) {
$scope.articles = articlesFactory.articles;
$scope.articles = [
{ title : 'foo', content : "foo", likes : 5, date : '12/15/2014' },
{ title : 'bar', content : "bar", likes : 2, date : '12/14/2014' },
{ title : 'baz', content : "baz", likes : 4, date : '12/23/2014' }
];
$scope.addArticle = function() {
if(!$scope.title || $scope.title === '') { return; }
$scope.articles.push(
{
title: $scope.title,
content: $scope.content,
likes: 0,
date: '12/15/2014',
comments: [
{ author: 'foo', comment: 'bar', upvotes: 0 }
]
}
);
$scope.title = '';
$scope.content = '';
}
$scope.likeArticle = function(article) {
article.likes += 1;
}
}]);
And here is my html file:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ibrahims Blog</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="app.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<style> .glyphicon-heart { cursor:pointer } </style>
</head>
<body ng-app="ibrahimsBlog">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
<form ng-submit="addArticle()" style="margin-top:30px;">
<h3>Create a new article!</h3>
<div class=form-group">
<input type="text"
placeholder="title"
ng-model="title">
</input>
</div>
<div class="form-group">
<input type="text"
placeholder="content"
ng-model="content">
</input>
</div>
<button type="submit" class="btn btn-primary">Hinzufügen</button>
</form>
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Ibrahims Blog</h1>
</div>
<span>
Go
</span>
</script>
<script type=text/ng-template" id="/articles.html">
<div class="page-header">
<h3> {{ article.title }} </h3>
</div>
<div ng-repeat="article in articles">
<span class="glyphicon glyphicon-heart"
ng-click="likeArticle(article)"></span>
{{ article.title }} - "{{ article.content }}" - Likes: {{ article.likes }}, Date: {{ article.date }}
</div>
</script>
</div>
</div>
</body>
</html>
Unfortunately everything I receive is following part of the html
<form ng-submit="addArticle()" style="margin-top:30px;">
<h3>Create a new article!</h3>
<div class=form-group">
<input type="text"
placeholder="title"
ng-model="title">
</input>
</div>
<div class="form-group">
<input type="text"
placeholder="content"
ng-model="content">
</input>
</div>
<button type="submit" class="btn btn-primary">Hinzufügen</button>
</form>
Edit
Unfortunately there is still a part which is not working.. When I use the Go button, I see the change of the URL, but it then instant redirects me to the home template. On the server I get a 404 Error. Do you know why this is happening?
I think you have a semi-colon in the wrong place when defining the $stateProvider. You aren't chaining the .state calls properly because the first semi-colon terminates the statement:
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'PrimaryController'
}); // <-------------------------Remove this semi-colon!
.state('articles', {
url: '/articles/{id}',
templateUrl: '/articles.html',
controller: 'ArticlesController'
});
Like chubbsondubs stated, I had to remove a semicolon. But since that was just a cause for one problem here is the other fault I found later on. In my template in this line
<script type=text/ng-template" id="/articles.html">
The quotation marks were missing! That was the reason for the 404. It should be like this:
<script type="text/ng-template" id="/articles.html">

How to get data from $http on the page?

I am writing a small test page that retrieves some data from a RESTful API I have previously written.
I can successfully retrieve this data from Angular, but I can't seem to find a way to display this data on the page. I am trying to loop over the list of results and print it in a table.
This is my index.html:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf8" >
<link rel="stylesheet" type="text/css" href="./css/bootstrap.css">
<script type="application/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.js"></script>
<script type="application/javascript" src="./js/URLSet.js"></script>
<script type="application/javascript" src="./js/app.js"></script>
</head>
<body ng-app="MyApp">
<div ng-controller="URLSetDAO as dao">
<button class="btn" ng-click="dao.list()">List</button>
<table class="table" ng-init="urlsets = dao.list()">
<td ng-repeat="urlset in urlsets">
<tr>
{{ urlset.pk }}
</tr>
<tr>
{{ urlset.user }}
</tr>
<tr>
{{ urlset.title }}
</tr>
<tr>
{{ urlset.views}}
</tr>
<tr>
{{ urlset.type }}
</tr>
</td>
</table>
</div>
</body>
</html>
This is the app.js:
(function() {
var app = angular.module('MyApp', ['URLSet']);
})();
And this is the URLSet.js:
(function() {
var app = angular.module('URLSet', []);
app.controller('URLSetDAO', ['$http', function($http){
var ip = "http://localhost:8000";
var store = this;
this.list = function() {
return $http({method: 'GET', url: ip + '/urlsets/'})
.success(function(data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
});
};
this.read = function(id) {
$http({method: 'GET', url: ip + '/urlsets/' + id})
...
};
this.create = function(obj) {
$http({method: 'POST', url: ip + '/urlsets/'})
...
};
this.update = function(id, obj) {
$http({method: 'PUT', url: ip + '/urlsets/' + id})
...
};
this.remove = function(id) {
$http({method: 'DELETE', url: ip + '/urlsets/' + id})
...
};
}]);
})();
I understand that Promises work similarly to callbacks, so it's asynchronous. So how am I able to display this data, if ng-init will not wait for the function to finish?
EDIT:
Besides the fact that I inverted the tr and td tags (thanks to satish for suggesting Plunker, which pointed me this error), making the table render invisible (so I would never see the results on the page), I also injected $scope into my controller.
It is like this now:
...
app.controller('URLSetDAO', ['$http', '$scope', function($http, $scope){
var ip = "http://localhost:8000";
var store = this;
this.list = function() {
$http({method: 'GET', url: ip + '/urlsets/'})
.success(function(data, status, headers, config) {
$scope.urlsets = data;
})
.error(function(data, status, headers, config) {
});
};
...
And index.html:
<body ng-app="MyApp">
<div ng-controller="URLSetDAO as dao">
<button class="btn" ng-click="dao.list()">List</button>
<table class="table" ng-init="dao.list()">
<tr ng-repeat="urlset in urlsets">
<td>
{{ urlset.pk }}
</td>
<td>
{{ urlset.user }}
</td>
<td>
{{ urlset.title }}
</td>
<td>
{{ urlset.views}}
</td>
<td>
{{ urlset.type }}
</td>
</tr>
</table>
</div>
</body>
One way to solve this is to drop the ng-init and do that in your controller instead:
For example:
app.controller('URLSetDAO', ['$http', '$scope', function($http, $scope){
var ip = "http://localhost:8000";
var store = this;
this.list = function() {
return $http({method: 'GET', url: ip + '/urlsets/'})
.success(function(data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
});
};
this.list().success(data) {
$scope.urlsets = data;
});
...
});
Hope this helps.

Resources