API call on click of link in angular JS - javascript

I am trying to call an api on click of a link and show the data in a new view , but i am not seeing any data neither an error on console.I tried using Log also but thats also not giving me any clue.
Here is my code in View:
<tr class="well-new" ng-repeat="product in gettempdata.FoodItems| orderBy:'Id' | filter:search"">
<td class="tdCenter" >
{{product.Id}}
</td>
<td class="tdCenter">
<img ng-src="{{product.ImageUrl}}" alt="{{product.Name}}" />
</td>
<td>
<b>{{product.Name}}</b><br />
{{product.Category}}
</td>
</tr>
</table>
I am trying to call GetItemDetails(Id).
Controller code:
myStore.controller("Home", function ($scope, StoreService, $log, $window) {
var onComplete = function (data) {
$scope.gettempdata = data;
}
var onError = function (reason) {
alert(reason.errorcode);
}
$scope.GetItemDetails = function (Id) {
$log.info("wait for 5 secs");
StoreService.getItemDetails(Id).then(onComplete, onError);
$log.info("done");
}
});
App.js code:
var myStore = angular.module('groceries', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider.
when("/Home", {
templateUrl: "/Index.html",
controller: "Home"
}).
when("/Name", {
templateUrl: "Store/Product.html",
controller: "Home"
}).
otherwise
({
redirectTo: "/Home"
})
});
The Home view:
<html ng-app="groceries">
<head>
<script> ALL scripts</scripts>
<title></title>
</head>
<body>
<!--
bootstrap fluid layout
(12 columns: span 10, offset 1 centers the content and adds a margin on each side)
-->
<div class="container-fluid">
<div class="row-fluid">
<div class="span10 offset1">
<h1 class="well">
<b>Store </b>
</h1>
<!-- Click here to navigate to Store-->
<div ng-view ></div>
</div>
</div>
</div>
</body>
</html>

Please check the case of the variables, .id instead of .Id
{{product.id}} {{product.imageUrl}}{{product.name}}{{product.category}}

Anchor tag has precedence for href over ng-click and so that won't work.
I modifed my code as below:
<td >
<a ng-href="" ng-click="GetItemDetails(product.Id,window.location.href='/Name')"><b>{{product.Name}}</b></a><br /></td>

Related

Failed initializing html tab with server data

I am creating an html page with two tabs. When you click on tab 1, it loads table data 1. When you click on tab 2,
it loads table data 2. Tab 1 is working as expected. However, when I click on tab 2, the data isn't loaded. The controllers
are identical. What is the difference?
Here is the relevant html code. tab with id "tableData" loads with data and tab with id "correlations" doesn't load.
<div>
<ul class="nav nav-tabs" role="tablist">
<li role="presentation">Table Data</li>
<li role="presentation">Correlations</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="tableData">
<h2 class="sub-header">Health Data</h2>
<div class="table-responsive" data-ng-app="myApp" data-ng-controller="journalCtrl">
<div data-ng-include="'screens/tablescreen.html'"></div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="correlations">
<h2 class="sub-header">Correlations Data</h2>
<div class="table-responsive" data-ng-app="correlationsApp" data-ng-controller="correlationsCtrl">
<div data-ng-include="'screens/tablescreen.html'"></div>
</div>
</div>
</div>
</div>
Here is my correlationsCtrl. init() is never invoked. Why?:
var correlationsApp = angular.module('correlationsApp', []);
correlationsApp.controller('correlationsCtrl', function ($scope, $http) {
$scope.init = function () {
$http.get("https://localhost:4567/foo/1/correlations")
.then(function (response) {
var json = response.data.records;
$scope.records = json;
$scope.headers = response.data.headers;
});
};
//This is not invoked. Why?
$scope.init();
});
Here is my controller which does get invoked:
var app = angular.module('myApp', []);
app.controller('journalCtrl', function ($scope, $http) {
$scope.init = function () {
$http.get("https://localhost:4567/journal/1")
.then(function (response) {
var json = response.data.records;
$scope.records = json;
$scope.headers = response.data.headers;
});
};
//This is invoked on page load. Why does this work and the other doesn't?
$scope.init();
});
Here is the html table:
<table class="table table-striped">
<thead>
<tr>
<th data-ng-repeat="header in headers">{{header}}</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="record in records track by $index">
<td data-ng-repeat="header in headers">{{ record.data[header] }}</td>
</tr>
</tbody>
</table>
In html you declare data-ng-controller="fooCtrl" but you have no controller fooCtrl. No need to declare two different module for two tabs you can declare two controller for two tabs in same module.
like:
var app = angular.module('myApp',[]);
app.controller('correlationsCtrl', function ($scope, $http) {
$scope.init = function () {
// your code
};
$scope.init();
}).controller('journalCtrl', function ($scope, $http) {
$scope.init = function () {
// your code
};
$scope.init();
});
so you use ng-app = "myApp" in root element like <html ng-app="myApp"> or <body ng-app="myApp"> and use only data-ng-controller in your tab page.
<div class="table-responsive" data-ng-controller="journalCtrl">
<div data-ng-include="'screens/tablescreen.html'"></div>
</div>
and
<div class="table-responsive" data-ng-controller="correlationsCtrl">
<div data-ng-include="'screens/tablescreen.html'"></div>
</div>
See PLUNKER DEMO two tabs show data from two different controllers.

ng-repeat throwing invalid Expression

I'm a total angular noob and trying to create a simple test app where. I'd like to read out some userdata in a partial. The user data is in my event controller. I assign the event controller to a form in my new.html partial after navigating to #/new via a route controller.
The error I get when trying to loop through the users in my partial is "Error: ngRepeat:iexp Invalid Expression". I can't figure out how to ng-repeat through those users.
Any thoughts?
My index.html:
<div class="container" style="width: 500px; margin: 0 auto;">
<ul class="nav nav-pills" ng-controller="NavigationController as navigationCtrl">
<li ng-class="{active: navigationCtrl.isActive(1)}">
Home
</li>
<li ng-class="{active: navigationCtrl.isActive(2)}">
Nieuw
</li>
<li ng-class="{active: navigationCtrl.isActive(3)}">
Nog een
</li>
</ul>
<div ng-view></div>
</div>
My new.html partial
<form action="" ng-controller="EventController as event">
<div ng-repeat="users as user">
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="user.name">
<br>
<label>Emailaddress</label>
<input type="email" class="form-control" name="email" ng-model="user.email">
<br>
<input class="btn btn-default" type="submit" ng-click="event.addEvent($event)" value="Klik">
</div>
</form>
And last: My angular code
(function () {
var app = angular.module('testApp', ['ngRoute']);
app.controller('NavigationController', ['$scope', '$route', function ($scope, $route) {
$scope.$route = $route;
this.activeTab = 1;
this.setActiveTab = function (tab) {
this.activeTab = tab;
};
this.isActive = function (tab) {
if ($route.current && $route.current.activeTab) {
return $route.current.activeTab === tab;
}
return false;
};
}]);
app.controller('EventController', ['$scope', '$controller', function ($scope, $controller) {
this.users = [
{name: 'aa'},
{name: 'bb'}
];
this.addEvent = function (e) {
e.preventDefault();
console.log(this);
};
}]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/new', {
templateUrl: 'partials/new.html',
controller: 'NavigationController',
activeTab: 2
}).
when('/another', {
templateUrl: 'partials/another.html',
controller: 'NavigationController',
activeTab: 3
}).
otherwise({
redirectTo: '/',
controller: 'NavigationController',
activeTab: 1
});
}]);
})();
I've tried changing this for $scope to no avail.
You write ng-repeat in wrong way in your new.html partial page
it should be like
new.html
<div ng-repeat="user in users">
Correct syntax for ng-repeat is
<element ng-repeat="item in [1,2,3]">
Also you can use things like track by $index if you have duplicated values in your collection like [1,1,1].
Ref. https://docs.angularjs.org/api/ng/directive/ngRepeat
There are few issues in your code. Please change all this references to $scope and then quickly fix below html code:
<div ng-repeat="user in users">
It should work but update me otherwise also.
Working demo for your reference (route codes excluded for demo purpose only)
thanks,
Ashok
you have not written ng-repeat in right way change it to:
<div ng-repeat="user in users">

ng-click in angular directive

I cannot figure out why my ng-click inside of my directive will not fire the fooControls clickTest. Why is clickTest not firing and logging to the console? is there a better way of doing this?
Directive
app.directive('fooList', function () {
return {
restrict: 'E',
templateUrl: './app/views/fooList.html',
scope: { obj: "=" },
controller: 'fooController',
controllerAs: 'b'
};
});
Controler
app.controller('fooController', ['$scope', function ($scope) {
$scope.obj = [];
$scope.ClickTest = function (num) {console.log(num);};
}]);
HTML
<div ng-repeat="book in obj" class="container">
<div class="row">
<h4 class="pull-right"><button class="btn btn-small" ng-click="b.ClickTest(1)">ClickTest</button></h4>
</div>
<br />
</div>
EDIT
The above html is a copy paste of foo-list. The full html is
<html>
<head>
</head>
<body>
<foo-list obj="searchResults"></foo-list>
</body>
<html
Your html should be changed to have the ClickTest function applied directly to the scope, not a variable in the scope. You also need to include a <foo-list /> tag for your directive.
<div ng-repeat="book in obj" class="container">
<div class="row">
<!-- Change b.ClickTest(1) to ClickTest(1)-->
<h4 class="pull-right"><button class="btn btn-small" ng-click="ClickTest(1)">ClickTest</button></h4>
</div>
<br />
<!-- Insert a foo-list tag -->
<foo-list obj="searchResults"></foo-list>
</div>

Books Won't Display for Reader App Exercise

I'm trying to get books to display based on the assignment above but can't figure out what is wrong for the life of me.
I built the service and modified the controller and view pages to the point where I believe they should display the books in the view, but I'm just seeing a blank page.
I feel like I am probably not retrieving the data properly and accessing it in the view/html.
Any ideas? Link to jsFiddle.
Index.html
<body ng-app="ReaderApp">
<div class="header">
<div class="container">
Reader
</div>
</div>
<div class="main">
<div class="container">
<div ng-view></div>
</div>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/BookshelfController.js"></script>
<script src="js/controllers/BookController.js"></script>
<script src="js/controllers/ChapterController.js"></script>
<!-- Services -->
<script src="js/services/books.js"></script>
</body>
js/apps.js
var app = angular.module('ReaderApp', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/books', {
controller: 'BookshelfController',
templateUrl: 'views/bookshelf.html'
})
.otherwise({
redirecTo: '/books'
});
});
js/services/books.js
app.factory('books', ['$http', function($http) {
return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/books-api/books.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
js/controllers/BookshelfController
app.controller('BookshelfController', ['$scope', 'books', function($scope, books) {
books.success(function(data) {
$scope.myBooks = data;
});
}]);
js/views/bookshelf.html
<div class="bookshelf row">
<!--
TODO: Loop through myBooks and display each one with this HTML
<div class="book col-md-3">
<a href="#/books/{{$index}}">
TODO: Add the book's cover here
<h3 class="title"> </h3>
<p class="author"> </p>
</a>
</div>
-->
<div class="book col-md-3" ng-repeat="book in myBooks">
<a href="#/books/{{$index}}">
<img ng-src="{{ book.cover }}">
<h3 class="title">{{ book.title }}</h3>
<p class="author">by {{ book.author }}</p>
</a>
</div>
</div>
I think I had the same trouble and my problem was in the router. Try adding array brackets ( [ ] ) and the '$routeProvider' string in your config method (app.js) like this:
app.config(['$routeProvider', function($routeProvider) {
// Normal router stuff goes here
}]);
Coming from Ember, the syntax is a little weird so I've been using this tutorial as reference when I get stuck.

AngularJS show login/logout button conditionally in navbar on app page

Main.jsp
<html>
<body ng-app="myApp">
<div class="navbar">
View Orders
<a href="/logout" ng-show="$scope.isUserLoggedIn"> Logout </label>
<a href="/login" ng-show="!$scope.isUserLoggedIn"> Login </label>
</div>
<div ng-view></div>
</body>
</html>
Controllers
var myApp = angular.module('myApp', ['ngRoute']);
...
// route for the default home page
.when('/', {
templateUrl : function($node, tattrs) {
return "resources/html/home.html";
},
controller : 'mainController'
})
// route for the order page
.when('/order', {
templateUrl : function($node, tattrs) {
return "resources/html/order.html";
},
controller : 'orderController'
})
....
myApp.controller('mainController', function($scope, $http) {
....
$scope.isUserLoggedIn = true; //or false
.....
Question:
The $scope.isUserLoggedIn is having no effect on Login/Logout hrefs. The scope is probably not accessible on the main app page (i.e in the navbar in the ng-app page).
I want to show hide the Login/Logout button conditionally. Any ideas?
You are missing assigning controller to div
No need to use $scope there, just use
<div class="navbar" ng-controller="mainController">
View Orders
<a href="/logout" ng-show="isUserLoggedIn"> Logout </label>
<a href="/login" ng-show="!isUserLoggedIn"> Login </label>
</div>

Categories

Resources