Data Binding is not working with Ionic Cards - angularjs

Alright, I have an html page that contains an ionic card but when I bind data to its items they are not shown at the browser so what is the problem
<ion-view title="Game" ng-controller="GameCtrl as vm">
<ion-content class="has-header">
<div class="card">
<div class="item">
Home Team
</div>
<div class="item">
{{vm.game.team1}}
</div>
<div class="item">
Score: {{vm.game.team1Score}}
</div>
</div>
<div class="card">
</div>
<div class="card">
</div>
</ion-content>
</ion-view>
and here is the angular controller for this page :
(function () {
'use strict';
angular.module('eliteApp').controller('GameCtrl', ['$stateParams','eliteApi', GameCtrl]);
function GameCtrl($stateParams, eliteApi) {
var vm = this;
var gameId = Number($stateParams.id);
var data = eliteApi.getLeagueData();
vm.game = _.find(data.games,{"id": gameId});
};
})();
I injected the js file to index.html; while tracing the debugging the function is getting data but data is not viewed at the browser so can anybody have some help ?

Try this:
'use strict';
angular.module('eliteApp').controller('GameCtrl', ['$stateParams','eliteApi', function($stateParams, eliteApi){
var gameId = Number($stateParams.id);
var data = eliteApi.getLeagueData();
this.game = _.find(data.games,{"id": gameId});
}]);
Edit
Looks like you're missing a route with a game id. Add this to your .config function:
.state('app.game-detail', {
url: "/game/:id",
views: {
"mainContent":{
templateUrl: "app/game/game.html"
}
}
})
And change your team-detail.html with this:
<a class="item item-icon-right" ng-repeat="game in vm.games"
href="#/app/game/{{game.gameId}}">
It should work now.

Related

Update view when api get data in Angularjs

So, i have a little problem. I made a tiny webapp that uses the omdb api. The thing is this that when i type in the movie that i'm searching for then press the search button, the view should change to the result.html view and show the data i got from the api.
The api works fine. I got the data to display, but that was in my index.html. Now i have splitted the files by using ng-routes
I can provide you the whole project if you wanna look at it. Maybe i can upload it to a online editor somewhere?
This is my app.js
var myApp = angular.module("myApp", ['ngRoute']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'views/home.html',
controller: 'filmController'
}).
when('/result', {
templateUrl: 'views/result.html',
controller: 'filmController'
}).otherwise({
redirectTo: '/home'
})
}]);
myApp.controller("filmController", function filmController($scope, $http, $window) {
$scope.getData = function () {
var movieTitle = document.getElementById("filmName").value;
var binding = document.getElementsByClassName("ng-binding");
$http
.get("http://www.omdbapi.com/?t=" + movieTitle + "&apikey=526345a6")
.then(function (response) {
var data = response.data;
if (data.Error) {
alert("Film inte funnen");
return false;
}
for (let key in data) {
if (data.hasOwnProperty(key)) {
let element = data[key];
if (element === "N/A") {
data[key] = "Inget hittat";
if (key === "Poster") {
$scope.post = "Ingen poster hittad";
}
}
$scope.url = data;
}
}
if (data.Ratings.length === 0) {
$scope.rate = "Ingen utmärkelse/er hittad";
}
// This api data is printed to the console on the index.html view, i want it in the result view...
console.log(data);
});
};
});
This is my index.html
<body>
<div class="main-content">
<!-- <div class="container">
<div class="row">
<div ng-controller="MyController">
<div ng-repeat="item in larare" class="col-lg-12">
<div class="card">
<img ng-src="/images/{{item.shortname}}.jpg" alt="Bild på {{item.name}}" class="card-img-top">
<div class="card-body">
<h3 class="card-title">{{item.name}}</h3>
<p class="card-text">{{item.reknown}}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div> -->
<header ng-include="'header.html'"></header>
<main ng-view></main>
</div>
</div>
<script>
var elem = document.getElementsByTagName("body")[0];
if (elem.requestFullscreen) {
elem.requestFullscreen();
console.log("Nu");
} else {
console.log("Error");
}
function updateSite(event) {
window.applicationCache.swapCache();
}
window.applicationCache.addEventListener('updateready',
updateSite, false);
</script>
<script src="./js/formvalidation.js"></script>
</body>
</htm>
And my result view
<div class="show container" ng-show="url.Title">
<div class="poster">
<!-- <img ng-src="{{ url.Poster }}" alt="" /> -->
<img ng-src="{{ url.Poster == 'Inget hittat' ? './images/image_not_found.png' : url.Poster }}">
<p class="text-dark">{{ post }}</p>
</div>
<h2 class="text-dark">{{ url.Title | uppercase}}</h2>
<div class="movie-info">
<p class="text-dark">
<strong>Från:</strong> {{ url.Year }}</p>
<p class="text-dark">
<strong>Rating:</strong> {{ url.Rated }}</p>
<p class="text-dark">
<strong>Utgiven:</strong> {{ url.Released }}</p>
<p class="text-dark">
<strong>Längd:</strong> {{ url.Runtime }}</p>
</div>
<p class="text-dark">
<strong>Skådespelare:</strong> {{ url.Actors }}</p>
<p class="text-dark">
<strong>Regissör:</strong> {{ url.Director }}</p>
<p class="text-dark">
<strong>Utmärkelser:</strong> {{ url.Awards }}</p>
<p class="text-dark">
<strong>Handling: </strong> {{ url.Plot }}</p>
<h4 class="text-dark">
<strong>Utmärkelser</strong>
</h4>
<p class="text-dark ">{{ rate }}</p>
<div ng-repeat="rating in url.Ratings | orderBy: '-Value'">
<p class="text-dark">
<strong>{{ rating.Source + ': ' + rating.Value }}</strong>
</p>
</div>
This is my home view
<section class="text-white">
<img src="./images/background.jpg" alt="Bild på poster från Frankenstein filmen" class="bg-image">
<div class="main container align-middle">
<div class="row text-center justify-content-center section-intro">
<div class="col-6 mb-5">
<h1>Filmtipset</h1>
<h5>Sök efter dina favortfilmer</h5>
</div>
</div>
<form ng-submit="getData()">
<div class="inputSearch mx-auto">
<div class="row justify-content-center">
<div class="col-8">
<div class="form-group">
<label for="filmName">Film</label>
<input class="form-control" type="text" name="filmName" id="filmName" placeholder="Ex. Armageddon" autofocus>
</div>
<input type="submit" class="btn btn-primary btn-lg btn-block btn-info mt-5" onclick="validateForm()" ng-click="'#!/result'">
</div>
</div>
</form>
Just a few notes before we break down the issue you are seeing. It seems like you aren't using angularjs to its full potential. Using a mixture of jquery and angularjs is not best practice and can make debugging very difficult. I would recommend making movieTitle an ng-model, as well as using angularjs's built in form validation. This will allow you to access the movieTitle easily in your controller as well as take advantage of angular's built in form controller and actions.
As for getting the data to your other page, I would add a second controller for that page, then from your filmController, you can pass the movie title as a route param when changing views. In your resultController, you can get the movie title from the route param and then do your api call while initializing the result page/controller.
In your home.html file, we will add ng-model to the input to be more angularjs friendly. Now we can access movieTitle in the controller with $scope.movieTitle. I am also changing the method that should get run on submit to the search() method I have added to the filmController.
home.html
<form ng-submit="search()">
// ... your other html here
<input class="form-control" type="text" name="filmName" id="filmName" ng-model="movieTitle" placeholder="Ex. Armageddon" autofocus>
In your filmController, I would add $location and move the getData() method to a resultController. We will now call search() on form submit, then use $location to switch views to your result view, attaching the movie title as a route param so we can access it in the resultController.
filmController.js
myApp.controller("filmController", function filmController($scope, $http, $location) {
// ... other code you have
// this will be what gets called after the user types a movie title
$scope.search = function () {
var title = $scope.movieTitle; // or using jquery(not recommended)
// this will change location and will produce
// the url: http://[yoursite]/result?movieTitle=title
$location.path('/result').search({movieTitle: title});
}
});
In your newly created resultController, we will get that route param and use it to search for the data.
resultController.js
myApp.controller("resultController", function resultController($scope, $http, $routeParams) {
// the getData method moved to this controller
$scope.getData = function (movieTitle) {
$http
.get("http://www.omdbapi.com/?t=" + movieTitle + "&apikey=526345a6")
// the rest of your code for getData here
};
// I like to make an init method to make it clear what we are initializing
$scope.init = function () {
// this will get the movieTitle from the /result?movieTitle=title part of your url
var movieTitle = $routeParams['movieTitle'];
// now we call the method you have that uses the omdb api
// just modify it to accept the movie title as a param rather than finding it in the html
$scope.getData(movieTitle);
}
// run init method
$scope.init();
});
Finally, you will want to update your app config to have your result route use the resultController we added instead of the filmController.

it just keep loading the same page with angular ngRoute?

I am learning angular by building a simple bookstore web app using nodejs as a restful api server. I built the server and it works fine, but once it comes to the front end I face an issue. I built the main page using angular ngRoute to get the data from the server and presented as following:
the picture and the title and the description angular read it with no problem but once I press the button "View Details" I should be redirected to a details page using the book id from the server.
From the front End the route provider:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider){
$routeProvider.when('/',{
controller: 'BooksController',
templateUrl: 'views/books.html'
})
.when('/books',{
controller: 'BooksController',
templateUrl: 'views/books.hrml'
})
.when('/books/details/:id',{
controller: 'BooksController',
templateUrl: 'views/book_details.html'
})
.when('/books/add', {
controller: 'BooksController',
templateUrl: 'views/add_book.html'
})
.when('/books/edit/:id', {
controller: 'BooksController',
templateUrl: 'views/edit_book.html'
})
.otherwise({
redirectTo: '/'
})
});
Books Controller:
var myApp = angular.module('myApp');
myApp.controller('BooksController', ['$scope', '$http', '$location',
'$routeParams', function($scope, $http, $location, $routeParams){
console.log('BooksController loaded...');
$scope.getBooks = function(){
$http.get('/api/books').then(function(response){
$scope.books = response.data;
});
}
$scope.getBook = function(){
var id = $routeParams.id;
$http.get('/api/books/'+id).then(function(response){
$scope.book = response.data;
});
}
}]);
books html where the panel being designed:
<div class="panel panel-default" ng-init="getBooks()">
<div class="panel-heading">
<h3 class="panel-title">Latest Books</h3>
</div>
<div class="panel-body">
<div class="row">
<div ng-repeat="book in books">
<div class="col-md-6">
<div class="col-md-6">
<h4>{{book.title}}</h4>
<p>{{book.description}}</p>
<a class="btn btn-primary"
href="#/books/details/{{book._id}}">View Details</a>
</div>
<div class="col-md-6">
<img class="thumbnail" src="{{book.image_url}}">
</div>
</div>
</div>
</div>
</div>
</div>
This the details book html where by clicking the button it must be redirected to:
details_book.html
<div class="panel panel-default" ng-init="getBook()">
<div class="panel-heading">
<h3 class="panel-title">{{book.title}}</h3>
</div>
<div class="panel-body">
<div class "row">
<div class ="col-md-4">
<img src="{{book.image_url}}">
</div>
<div class ="col-md-8">
<p>{{book.description}}</p>
<ul class="list-group">
<li class="list-group-item">Genre: {{book.genre}}</li>
<li class="list-group-item">Author: {{book.author}}</li>
<li class="list-group-item">Publisher: {{book.publisher}}
</li>
</ul>
</div>
</div>
</div>
</div>
and this is the get request from the server to prove the server working find using a certain id
The error I get once I open the main page:
And this error I get once I press the button:
Note: Once I press the button it give me this url:
http://localhost:3000/#!/#%2Fbooks%2Fdetails%2F599701c1f3da51117535b9ab
where the id is 599701c1f3da51117535b9ab which we can see it in the end of the url. But it should give url exactly such as:
http://localhost:3000/#!/books/details/599701c1f3da51117535b9ab
and once I write this url manually I get to the page which is the details with no problem but once I press the button from the book.html page I get the previews strange url again which is:
http://localhost:3000/#!/#%2Fbooks%2Fdetails%2F599701c1f3da51117535b9ab
Which load no where.
This is the github url for all the documents:
https://github.com/AbdallahRizk/BookStore.git
Any suggestions Please!!
use $rootScope instead of $scope for getBook function
$rootScope.getBook = function(){
var id = $routeParams.id;
$http.get('/api/books/'+id).then(function(response){
$scope.book = response.data;
});
init(getBook);
}
Note: add $rootScope to your BookController
Seems like I have hashprefix !, then my URL should also have ! after hash(#)
href="#!/books/details/{{book._id}}"
Since Angular 1.6 hashprefix is defaulted to !, you can disable this behavior by setting hashPrefix to ''(blank).
.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('');
}
]);
Note: This answer from, #Pankaj Parkar at I get a weird templateURL not as it suppose to give with angular?

How to get param from one controller to another?

My question is best explained when I straight go to the code.
HTML part:
<div class="panel panel-default post" ng-repeat="post in posts">
<div class="panel-body">
<div class="row">
<div class="col-sm-2">
<a class="post-avatar thumbnail" href="/profile#/{[ post.profileID ]}">
<div class="text-center">{[ user.fullname ]}</div>
</a>
</div>
</div>
</div>
When I click on the /profile#/{[ post.profileID ]} link - it takes me to the profile page. All good here.
However, I am using ngView so I have separated it like this:
<div class="col-md-3">
<div>Some HTML stuff</div>
</div>
<div class="col-md-6">
<div ng-view></div>
</div>
<div class="col-md-3">
<div>Some HTML stuff</div>
</div>
My ngView makes use of the /profile#/{[ post.profileID ]} param and I use it to display whatever I have to display.
The problem:
I can get the profileID param in my angular controller but once I get it, how will I be able to pass it onto other controllers?
My controller looks like the below:
var profileApp = angular.module('profileApp', ['ngRoute']);
profileApp.config(function($routeProvider) {
$routeProvider
.when('/:id', {
templateUrl : 'partial/profile/feed.html',
controller : 'mainController'
})
.when('/posts:id', {
templateUrl : 'partial/profile/posts.html',
controller : 'postsController'
});
});
profileApp.controller('mainController', ['$scope', '$http', '$routeParams', function($scope, $routeParams){
console.log($routeParams.id);
}]);
profileApp.controller('postsController', ['$scope', '$routeParams', function($scope, $routeParams){
console.log($routeParams.id);
}]);
As you can see, I get get the param passed from the HTML link and use it in the mainController but how will I get the param to be a link in the col-md-3 (just like the original /profile#/{[ post.profileID ]})?
Hope this makes sense. It's has been driving me nuts!
Thanks
Why don't you just edit your partial HTML pages and put the columns in it.
For partial/profile/feed.html :
<div>
<div class="col-md-6">
<div>feed stuff</div>
</div>
<div class="col-md-3">
</div>
</div>
And partial/profile/posts.html could be :
<div>
<div class="col-md-6">
</div>
<div class="col-md-3">
<div>posts stuff</div>
</div>
</div>
So I did some research into this and I just ended up using services.
See below for the answer:
profileApp.service('globalParams', function() {
var profileID = '';
return {
getProfileID: function() {
return profileID;
},
setProfileID: function(value) {
profileID = value;
}
};
});
You then pass the service into the dependencies in the controllers, like below:
profileApp.controller('mainController', ['$scope', 'globalParams', function($scope, globalParams){
//some code
};
And you can call the functions for getting and setting the variables.

couldn't figure out the issue with angular routing / ng-repeat.

The aboutus.html page is displayed correctly, except the content in the ng-repeat within media-list in aboutus.html. there are no errors displayed in the console. I have not included the entire code (since it takes more space.). Can anyone help me?
// factory here.
angular.module('vasuapp')
.factory('corporateFactory', function() {
// Implement two functions, one named getLeaders,
// the other named getLeader(index)
// Remember this is a factory not a service
var corpfac = {};
var leadership = [
{
id: 0,
name:"asdfd",
designation:"sgsdgg",
abbr: "fgdfvf",
},
{
// similarly some other data here.
} ];
corpfac.getLeader = function(){
return leadership;
};
corpfac.getLeaders = function(index)
{
return leadership[index];
};
return corpfac;
});
// app.js
angular.module('vasuapp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/aboutus', {templateUrl:'./aboutus.html' , controller: 'AboutController'})
.otherwise('/');
})
// controller.js
angular.module('vasuapp')
.controller ('AboutController',['$scope','corporateFactory', function($scope,corporateFactory){
var leadership = corporateFactory.getLeader();
$scope.leaders = this.leadership;
}])
// aboutus.html
<div class="row row-content">
<div class="col-xs-12 col-sm-9">
<h2>Corporate Leadership</h2>
<p> hi </p>
<ul class="media-list">
<li class = "media" ng-repeat = "lead in leaders">
<div class = "media-list tab-pane fade in active">
<a ng-href="#/aboutus">
<img class = "media-object" ng-src={{lead.image}} alt="author image">
</a>
</div>
<div class = "media-body">
<p>{{lead.description}}</p>
</div>
<footer>
-- {{lead.name}} the {{lead.designation}}
</footer>
</li>
</ul>
</div>
I think what you want is:
$scope.leaders = corporateFactory.getLeader();
this.leadership is not defined.

Where and how to inject $stateParams?

I am trying to get an image and a text into the view "home" in a Single Page Application with Angular ui-router and $stateParams.
'use strict';
angular.module('confusionApp')
.controller('IndexController', ['$scope', '$stateParams', 'menuFactory', 'corporateFactory', function($scope, $stateParams, menuFactory, corporateFactory) {
var dish = menuFactory.getDish(parseInt($stateParams.id,10));
$scope.dish = dish;
var promo = menuFactory.getPromotion(parseInt($stateParams.id,10));
$scope.promo = promo;
$scope.leader = corporateFactory.getLeader($stateParams.abbr)
}])
.controller('AboutController', ['$scope', 'corporateFactory', function($scope, corporateFactory) {
$scope.leaders = corporateFactory.getLeaders();
}])
The menuFactory service works fine in a 'MenuController' both with a list and with a parameter (injection while 'submit'). The corporateFactory works fine in a list using the 'AboutController'. But I just can't find out how to inject the $stateParam while index.html opens with the view 'home.html.
<div class="container" ng-controller="IndexController">
<div class="row row-content">
<div class="col-xs-12 col-sm-3 col-sm-push-9">
<p style="padding:20px;"></p>
<h3 align=center>Our Lipsmacking Culinary Creations</h3>
</div>
<div class="col-xs-12 col-sm-9 col-sm-pull-3">
<h4>Implement the Featured Dish Here</h4>
<div class="media">
<div class="media-left media-middle">
<a>
<img class="media-object img-thumbnail"
ng-src={{dish.image}} alt={{dish.name}}>
</a>
</div>
</div>
<div class="media-body">
<h2 class="media-heading">{{dish.name}}
<span class="label label-danger">{{dish.label}}</span>
<span class="badge">{{dish.price | currency}}</span></h2>
<p>{{dish.description}}</p>
</div>
</div>
</div>
Would anybody help me, please?
don't use $stateParams
inject $state instead and then access
$state.params.wotever
Thanks for your precious help JB Nizet and danday74!
The problem was to let the template know the properties of which dish to show. The answers I found were in controllers.js. First, I had to correct an error, and then I created a $scope.property containing only the required dish:
var up = menuFactory.detDish(0);
$scope.up = up;
Then I could use {{up.image}}, {{up.name}} etc. in the template.

Resources