Show number of API hits on view with Angular JS - angularjs

I am a beginner at Angular JS and trying to understand this concept. I have a JSON API which consist of product list and have used $hhtp.get to fetch and show the output in the view.
All i want to understand, if the problem statement asks for showing the number of hits/calls made to API in HTML. How to do that.
Here is my sample code
var app = angular.module('FusionApp', []);
app.controller('HomeController', ['$scope', 'displayproducts', function ($scope, displayproducts) {
displayproducts.success(function (data) {
$scope.show = data.products;
//get the product count
$scope.productCount = $scope.show.length;
});
}]);
Here is the HTML view
<div ng-controller="HomeController">
<div class="form-group">
<span ng-model="productCount">Product Count: {{productCount}}</span> |
<span ng-model="apiCount">API Hits:</span>
<p><input type="text" ng-model="name" placeholder="Search by Name" /</p>
</div>
</div>
Appreciate if you guide here. Note displayProducts is the factory service call to return the data

Related

AngularJS Storing userID in post operation

Edit (to make it more clear) I currently have a post methode where I post a birdname and location to my mongodb. But inside this post methode I also want to add the userID of the person that is logged in and posting the capture.
This way I can link the capture posted by him/her to their account.
Edit 2: The id of the capture is set through mongodb. My intent is to add the userID (of the user that is logged in and doing the post opperation) to be added into it all.
I'm working with AngularJS and Mongodb and as Authentication system I have integrated Auth0.
The code I currently have is posted below:
// Api.js ($resource for where to store the capture):
/* global app */
app.factory('Api', ['$resource', function($resource){
return {
Capture: $resource('/api/captures/:id', {id: '#id'})
}
}])
// CaptureCtrl.js - I can retrieve the user's id as shown below (inside the console.log):
/* global app */
app.controller('captureCtrl',[ '$scope', 'Api', 'auth', function($scope, Api, auth){
$scope.form = {};
$scope.auth = auth;
console.log($scope.auth.profile.user_id);
$scope.addToDatabase = function() {
console.log('button clicked');
Api.Capture.save({}, $scope.form, function(){
$scope.form = {};
})
}
}]);
// Capture.html - I don't want to add a extra input seeing it should be done behind the scene (obviously):
<form class="well" name="addCapture">
<div class="form-group">
<label for="birdname">Birdname</label>
<input type="text" class="form-control" id="birdname" ng-model="form.birdname" required>
</div>
<div class="form-group move-down">
<label for="place">Picture taken in:</label>
<input type="text" class="form-control" id="place" ng-model="form.place" ng-autocomplete required>
</div>
<div class="form-group">
<button type="submit" class="btn margin-left btn-success" ng-click="addToDatabase()" ng-disabled="addCapture.$invalid">Add Customer</button>
</div>
</form>
How would I add this into the code?
I've tried a couple of options but I keep getting errors.

select option isn't adding object in ionic

I'm trying to add a mongoose object to another mongoose object using a select bar in a form. All the other key,value pairs insert correctly, even the checkbox bool, but the select-option combo won't save the I've done this before with no problem, but in ionic, it doesn't seem to want to work. Is there a work around or am I just messing something up in the code?
$scope.addProperty = function(prop){
console.log(prop);
Props.add(prop)
.then(function(res) {
console.log(res.data);
//window.location.reload();
})
.catch(function(error){
console.log(error);
});
};
<form method = "post" class="form-inline" role="form" action = "localhost:3000/managers/newApt">
<div class="form-group">
<label class="sr-only" >Tenants:</label>
<select ng-model="prop.tenants" class="column medium-3" ng-options="manager.name for manager in allManagers"> </select>
</div>
<div class="form-group">
<label class="sr-only">Address</label>
<input type="text" class="form-control" ng-model='prop.address'>
</div>
<button type="submit" class="btn btn-default" ng-click='addProperty(prop)'>Add Property</button>
</form>
try to use this video tutorial they use var controllerName = this, inside controller and reference methods and properties of the controller through var controllerName, for example this is a controller:
angular
.module('your-app-module')
.controller('ExampleController', function ($scope, $state) {
//This var is to bind methods and vars in view(html) to this specific controller
var ExmpleCtrl = this; //this is the var that is going to replace $scope
//NOTICE no $scope but rather ExmpleCtrl
ExmpleCtrl.goToState = function (state) {
$state.go(state);
};
});
Now in your html try:
<ion-view ng-controller="ExampleController as exmpleCtrl">
<ion-content>
<!-- notice how I use exmpleCtrl instead of $scope to access controller or to pass info -->
<div ng-click="exmpleCtrl.doSomething()">
</ion-view>
If you still have doubt check this short video (ignore it's for webstorm the way they bind the controller to the a variable inside controller referenced to this is what is useful): http://blog.jetbrains.com/webstorm/2014/03/angularjs-workflow-in-webstorm/

Not able to access ng-model variables when using ng-view

I have the following Form which I am including in the main app through ng-view
Form Snippet
<form action = "#" method="post" class="form-horizontal" id="commentForm" role="form">
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" type="text" ng-model="userComment" placeholder="New Discussion Topic" rows="5"></textarea>
</div>
</div>
<div class="form-group" id="div_submitComment">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn" type="button" id="submitComment" ng-click="vm.addComment()">Submit comment</button>
</div>
</div>
</form>
Upon clicking the submit button, the controller function will be called. In the controller function, I am not able to access the variable $scope.userComment
Controller Snippet
(function () {
'use strict';
angular
.module('app')
.controller('DiscussionBoardController', DiscussionBoardController);
DiscussionBoardController.$inject = ['UserService', '$rootScope', '$scope', '$cookieStore', 'AuthenticationService'];
function DiscussionBoardController(UserService, $rootScope, $scope, $cookieStore, AuthenticationService) {
function addComment() {
$.getJSON(
"http://localhost/DBoardPage/server/discussion-board/postComment.php", // The server URL
{ userName: $scope.currentUser , userComment:$scope.userComment , commentID:0 }, // Data you want to pass to the server.
$scope.addCommentResponse // The function to call on completion.
);
};
/*End - Discussion Board related Functions*/
}
})();
Though I know that a child scope will be created when we use ng-include, ng-view and ng-repeat, I am not getting an example to explain the usage.
Please let me know how I can get around this preoblem
Are you sure it isn't $scope.currentUser that doesn't exist? You are using a variable that isn't declared.
Try adding:
$scope.currentUser = "";
$scope.userComment = "";
Since you are using AngularJS it might be a better idea creating your function the Angular way.
$scope.addComment = function(){....
If it still doesn't work show more of your setup.

Select some data and then persist to next controller/view in Angularjs

I am bringing in some simple data via a service that uses angular-resource like so:
angular.module('InvoiceService',
['ngResource'])
.factory('InvoiceService', function ($resource) {
return $resource('data.json');
})
.controller("DashboardListCtrl", function (InvoiceService) {
var vm = this;
InvoiceService.query(function (data) {
vm.invoices = data;
});
vm.submit = function (form) {
console.log(form)
};
});
And the html:
<form name="invoices" role="form" novalidate>
<ul>
<li ng-repeat="invoice in vm.invoices">
<input type="checkbox" id="{{'id-' + $index}}" />
<p><strong>Order:</strong></p>
<p>{{invoice.order}}</p>
</li>
<input type="submit" value="Continue" ng-click="vm.submit(invoices)" />
</ul>
</form>
Everything works fine; the data is displays in the view as expected.
The question:
What I'd like to do is be able to select a checkbox, grab the bit of data associated with that checkbox, and pass it along to the next controller/view on submit. How can I do this?
So, what do I do next? Am I on the right track?
**EDIT: added all angular code to help clarify
Posting answer as reply too big to be useful.
You should be using $scope to isolate the controller's data from the rest of the page.
Read up about ng-model http://docs.angularjs.org/api/ng/directive/ngModel and how to use it to two-way-bind checkbox value to a controller variable. No need to use theFormName if you call $scope.submit = function() { } as your ng-model variable will be available in $scope already.
angular.module('InvoiceService',
['ngResource'])
.factory('InvoiceService', function ($resource) {
return $resource('data.json');
})
.controller("DashboardListCtrl", function ($scope, InvoiceService) {
InvoiceService.query(function (data) {
$scope.invoices = data;
});
$scope.submit = function () {
// FIXME to access a property of each $scope.invoices
console.log('checkbox1=' + $scope.invoices[0].checkbox1);
};
});
Then the HTML:
<form role="form" novalidate ng-controller="DashboardListCtrl"><!-- EDIT: added ng-controller=, remove name= -->
<ul>
<li ng-repeat="invoice in invoices"><!-- EDIT: remove 'vm.' -->
<input type="checkbox" id="{{'id-' + $index}}" ng-model="invoice.checkbox1" /><!-- EDIT: added ng-model= -->
<p><strong>Order:</strong></p>
<p>{{invoice.order}}</p>
</li>
<input type="submit" value="Continue" ng-click="submit()" /><!-- EDIT: remove 'vm.' -->
</ul>
</form>

how to call http request on ng-click event?

I am using angularjs on front end. I have two input boxes on index.html (namely first-name and last-name), and one button. On the click of button (ng-click="search()") I want to call an http GET request with first-name and last-name as parameters. And then I want to show the response in the same page in some other DIV tag. How would I achieve this?
HTML:
<div ng-app="MyApp" ng-controller="MyCtrl">
<!-- call $scope.search() when submit is clicked. -->
<form ng-submit="search()">
<!-- will automatically update $scope.user.first_name and .last_name -->
<input type="text" ng-model="user.first_name">
<input type="text" ng-model="user.last_name">
<input type="submit" value="Search">
</form>
<div>
Results:
<ul>
<!-- assuming our search returns an array of users matching the search -->
<li ng-repeat="user in results">
{{user.first_name}} {{user.last_name}}
</li>
</ul>
</div>
</div>
Javascript:
angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.user = {};
$scope.results = [];
$scope.search = function () {
/* the $http service allows you to make arbitrary ajax requests.
* in this case you might also consider using angular-resource and setting up a
* User $resource. */
$http.get('/your/url/search', { params: user },
function (response) { $scope.results = response; },
function (failure) { console.log("failed :(", failure); });
}
}]);

Resources