How to use URL parameters in a GET request with Angular? - javascript

I have very simple application that has two features. One, it lists all of the keys two, it is supposed to display one particular key (and the associated value).
Here is the first part that list the keys:
var app = angular.module('flipDaSwitch', ['ngRoute']);
app.controller('ListKeys', function($scope, $http) {
$scope.getKeys = function() {
$http.get('/api/keys').
success(function (data) {
$scope.buckets = data;
}).
error(function (data){
$scope.buckets = {}
});
};
});
I am wondering how could I get a particular key from the API. The current HTML:
<div name="listkeys" class="container">
<div class="starter-template">
<div ng-bind-html="message"></div>
<table class="table table-striped table-bordered table-condensed sortable" ng-init="getKeys()">
<tr>
<th>Bucket:</th>
</tr>
<tr ng-repeat="bucket in buckets">
<td>
<a ng-href="/show_key.html#/key/{{bucket}}">{{bucket}}</a>
</td>
</tr>
</table>
</div>
</div>
Obviously the show_key.html gets the key in the URL like this:
/show_key.html#/key/efd1ae55a5-random_string
I am not sure how could I issue a get request based on the URL parameters.

Inject $routeParams in controller:
app.controller('ListKeys', function($scope, $http, $routeParams) {
...
Docs
Also there is a bunch of questions about this.

Related

Angular $scope function not working outside of ng-repeat

I have a <table> element, at which I declared a controller (only one in the app at the moment). I also have a ng-repeat on <tr> in the <tbody> element, which is working just fine, creating multiple table rows as intended. In the controller i have some api calls which are called for single table rows and which work just fine, and a function called from one of the <th>'s in <thead>, which I can't get to work. I know it's a scope thing, but I just can't grasp what I'm doing wrong.
To sum it up:
simplified html fragment:
<table ng-controller='myController'>
<thead>
<tr>
<th>Username</th>
<th><button ng-click='doStuff()'>Do stuff</button></th>
</tr>
</thead>
<tbody>
<tr ng-repeat='user in users'>
<td>{{user.name}}</td>
<td><button ng-click='delete(user)'>Delete</button>
</tr>
</tbody>
</table>
simplified js fragment:
app.controller('myController', ['$scope', '$http', users, function($scope, $http, users) {
//api call to get users, working fine
users.getAll().success(function(data) {
$scope.users = data;
});
//api call to delete users, also working fine
$scope.delete = function(user) {
users.delete(user).success(function() {});
};
//can't get this to fire
$scope.doStuff = function() {
alert('I do stuff');
};
}]);
Any insight would be helpful, thanks in advance!
EDIT
I assume the issue is comming from one of the modules, so I copied the whole thing into a plnkr. Sorry for the styling, removed it for more code simplicity.
EDIT 2
After studying the plnkr I came to see that it was an unclosed <div> element in the <thead>. Ouch. Thanks for the replies, and please excuse my carelessness.
EDIT 3
An even more carefull study revealed, that the problem has in fact been also lying in poorly designed jasmine unit tests.
It appears to be firing. I've had to simulate the asynchronous loading of users, but that shouldn't make a difference. Can you add a snippet to demonstrate the issue?
angular.module('app', []).controller('myController', ['$scope', '$http', '$timeout',
function($scope, $http, $timeout) {
//api call to get users, working fine
$timeout(function() {
$scope.users = [{
name: 'A'
}, {
name: 'B'
}];
}, 1000);
//api call to delete users, also working fine
$scope.delete = function(user) {
console.log('delete', user);
};
$scope.doStuff = function() {
console.log('I do stuff');
};
}
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<div ng-app="app">
<table ng-controller='myController'>
<thead>
<tr>
<th>Username</th>
<th>
<button ng-click='doStuff()'>Do stuff</button>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='user in users'>
<td>{{user.name}}</td>
<td>
<button ng-click='delete(user)'>Delete</button>
</tr>
</tbody>
</table>
</div>

How to keep track of Array index in angularJS?

Very new to Angularjs. So I have some JSON files that I am reading into my webpage that contain and array of objects that are cars. What I am trying to do is have my "button" when pressed alert me to the data specific to that button.
The ng-repeat is running 8 times so that is the length of the array, but in angularJs i'm not sure how to basically store the array index for each time the ng-repeat passes in my button function.
This is my a snippet of my .html:
<div class="carTable table-responsive text-center" ng-controller="ButtonController" >
<table class="table specTable">
<thead>
<tr>
<th>Make</th>
<th>Model</th>
<th>Year</th>
<th>Color</th>
<th>Milage</th>
<th>Doors</th>
<th class="reserve">Horsepower</th>
<th>Price</th>
<th class="reserve"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cars in car | orderBy:'year'">
<td>{{cars.year}}</td>
<td>{{cars.model}}</td>
<td>{{cars.make}}</td>
<td>{{cars.color}}</td>
<td>{{cars.mileage | number}}</td>
<td>{{cars.doors}}</td>
<td>{{cars.horsepower}}</td>
<td>{{cars.price | number}}</td>
<td><div class="panel panel-default">Reserve</div></td>
</tr>
</tbody>
</table>
</div>
The portion in question is at the bottom where I have a Reserve "button"
I'm leaving out my JSON files, works properly there. I'm just not sure how to keep track of the array index as the ng-repeat does its thing.
Here is the angular:
(function(){
var app = angular.module("myReserveApp", []);
app.controller("ButtonController", ["$scope", "$window", function($scope, $window){
$scope.buttonPress = function(){
$window.alert(JSON.stringify($scope.car[0]));
}
}]);
var MainController = function($scope, $http, $window){
var onGatherBoatData = function(response){
$scope.boat = response.data;
};
var onError = function(reason){
$scope.error = "Could not fetch Boat Data";
};
var onGatherCarData = function(response){
$scope.car = response.data;
};
var onError = function(reason){
$scope.error = "Could not fetch Car Data";
};
var onGatherTruckData = function(response){
$scope.truck = response.data;
};
var onError = function(reason){
$scope.error = "Could not fetch Truck Data";
};
$scope.message = "Hello, Angular Here!";
};
app.controller("MainController", ["$scope", "$http", "$window", MainController]);
}());
Currently in the top portion of the code I just have it alerting object[0] but I want it to be specific to which button is pressed. Any help is appreciated, thank you.
$index refers to the index in ng-repeat. So if you want to pass your function the index in array on the button click, change buttonPress() to buttonPress($index)
you'll have to change your controller to something like the following:
$scope.buttonPress = function(index){
$window.alert(JSON.stringify($scope.car[index]));
}
To do the following, you can just pass the current data in the ngRepeat. Moreover,if you want the current index, the ngRepeat directive provide specials properties, as the $index, which is an iterator.
$scope.buttonPress = function(car, index){
//Retrieve current data of the ngRepeat loop
console.log(car);
//Current index of your data into the array
console.log(index);
}
Then you can call your function like this :
Reserve
First, thank you both for the quick responses. Both of these answers work. I found another way to do it as well before reading your posts.
<div class="panel panel-default">
Reserve:{{car.indexOf(cars)}}
</div>
Using (car.indexOf(cars)) gives me the same result
$scope.buttonPress = function(index){
$window.alert(JSON.stringify(index));
}
Now when I click on the "button" it sends me back the array index, so now I should be able to play with that data. Thank you again both, for your help.

Retrieving the id from Model to Controller in Angular JS

i have a table which is having the data retrieved from an api call from my memberController which is displayed inside ng-repeat and its working fine.
I need each Business Name of the member list to link to a separate page(edit_form.html) and display the id value, so that i can pass this along with the api call to get only this particular member detail. So i have added ng-init in my edit form page which calls the function test_funct when the page loads and retrieve each persons id there. unfortunately i am unable to retrieve the id value inside the function.
HTML Template
<div class="page" data-ng-controller="memberController">
<table>
<thead >
<tr>
<th>Business Name</th>
<th>Contact Name</th>
<th>Trade Balance</th>
<th>Cash Balance</th>
<th>Telephone</th>
<th>Account Number </th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="member in details | filter:search">
<td>{{member.businessname}}</td>
<td>{{member.person}}</td>
<td>{{member.balance_trade}}</td>
<td>{{member.balance_cash}}</td>
<td>{{member.telephone}}</td>
<td>{{member.accountnumber}}</td>
</tr>
</tbody>
</table>
</div>
I have the following controller
function memberController($scope, $http, $cookieStore) {
var token = $cookieStore.get('token');
var conId = $cookieStore.get('Cont_Id');
var exId = $cookieStore.get('ex_Id');
var member_list = "http://www.vb.com/functions/member_list.html?exchangeid=" + exId +
"&contactid=" + conId + "&token=" + token;
$http.get(member_list)
.success(function(response) {
$scope.details = response;
});
$scope.test_funct = function(id) {
$scope.myid = id;
alert($scope.myid); // getting undefined in alert, i expect the id(eg:1123)
}
}
edit_form.html
<div class="page" data-ng-controller="memberController">
<div class="panel-body" ng-init="test_funct()"></div>
</div>
Please assist me on this. Thanks in advance.
There are 2 things going on here.
First, you should separate controllers for the different views, so you end up with something like this:
<div class="page" data-ng-controller="memberController">
<table>
<!-- your whole big table here -->
</table>
</div>
And your editing form as follows:
<div class="page" data-ng-controller="editController">
<div class="panel-body"></div>
</div>
Notice that you now have two distinct controllers - your "editController" and your "memberController".
The second question then becomes, how do you transfer the selected ID from the list view ("memberController") to the edit view ("editController").
There are 2 ways of doing that.
First, you could use a service shared between the controller:
.factory('SelectedId',function() {
return {};
});
And then in your "member" view, you would set it upon clicking:
{{member.businessname}}
Notice the ng-click, which then needs a function in the memberController and the injected service:
.controller('memberController',function($scope,SelectedId) {
$scope.setId = function(id) {
SelectedId.id = id;
};
});
While the editController retrieves it:
.controller('editController',function($scope,SelectedId) {
$scope.id = SelectedId.id;
});
The above option works well, especially for complex things like shopping carts. If all you are doing is passing an ID, I would just stick it in the URL:
{{member.businessname}}
So that the ID is part of the URL. You then can retrieve it in the "editController":
.controller('editController',function($scope,$routeParams) {
$scope.id = $routeParams.member;
});
assuming you are using ng-route, and your route would look like:
$routeProvider.when('/pages/edit_form/:member',{templateUrl:'/route/to/template.html',controller:'editController'});
In html do that
<td>{{member.businessname}}</td>
...
In app.js or where you define route do that
.when('/edit/:memberid',
{
templateUrl:'partials/edit.html',
controller:'editController'
})
In controller you have to take this id by doing that
app.controller("editController",function($routeParams,$scope){
$scope.memberid= $routeParams.memberid;
//Now use this member id to fetch all data
});

Empty table rows with ng-repeat, AngularJS

I have input fields that you can submit, and the data that you entered is inserted into an database. This data is then looped out in a table with ng-repeat:
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Sträcka</th>
<th>Tid</th>
<th>Jämför</th>
</tr>
</thead>
<tr ng-repeat="info in test"><td>{{info.stracka}}</td><td>{{info.tid}}</td><td><input type="checkbox" id="{{info.id}}" class="checkboxfisk" ng-click="testa(info.id)"></tr>
</table>
The problem is that, When the database table is empty, and you are submiting data for the first time, 3 empty TR's rows are printed out, after you have hit submit. I used firebug to debug this, and the HTML look like this when I hover on the empty TR-rows:
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Sträcka</th>
<th>Tid</th>
<th>Jämför</th>
</tr>
</thead>
<tbody>
<tr class="ng-scope" ng-repeat="info in test">
<td class="ng-binding"></td>
<td class="ng-binding"></td>
<td>
<input id="" class="checkboxfisk" type="checkbox" ng-click="testa(info.id)">
</td>
</tr>
<tr class="ng-scope" ng-repeat="info in test">
<td class="ng-binding"></td>
<td class="ng-binding"></td>
<td>
</tr>
<tr class="ng-scope" ng-repeat="info in test">
<td class="ng-binding"></td>
<td class="ng-binding"></td>
<td>
</tr>
</tbody>
</table>
<form class="ng-pristine ng-invalid ng-invalid-required" novalidate="" ng-submit="submitForm(userForm.$valid)" name="userForm">
As you can see, there are td's with classname of ng-binding. What is this? Can anyone help me?
Here is my controller:
as.controller('Test', function($scope, $http, $rootScope, testFactory)
{
$http.get($rootScope.appUrl + '/nao/test/test')
.success(function(data, status, headers, config) {
$scope.test = data.data;
});
$scope.form = {};
$scope.checkboxes = [];
$scope.testa = function(id) {
$scope.checkboxes.push(id);
};
$scope.submitForm = function(isValid) {
if(isValid)
{
$http.post($rootScope.appUrl + '/nao/test', $scope.form)
.success(function(data, status, headers, config) {
console.log(data);
console.log($scope.form);
}).error(function(data, status) {
});
}
};
});
EDIT: The problem was in my backend. I've have forgotten to add a parameter that is returned after that the mysql query is executed.
I see two possibilities.
In first, you should initialize your test scope variable before the $http call (to ensure it is initialized even if http request fails). And then create a method updateTest which will be called on succes of the submit form (to update test variable).
Your code should be like that:
as.controller('Test', function($scope, $http, $rootScope, testFactory)
{
// METHOD to update test items
updateTest = function() {
$http.get($rootScope.appUrl + '/nao/test/test')
.success(function(data, status, headers, config) {
$scope.test = data.data;
});
};
// init variables
$scope.form = {};
$scope.checkboxes = [];
$scope.test = [];
$scope.testa = function(id) {
$scope.checkboxes.push(id);
};
$scope.submitForm = function(isValid) {
if(isValid)
{
$http.post($rootScope.appUrl + '/nao/test', $scope.form)
.success(function(data, status, headers, config) {
console.log(data);
console.log($scope.form);
// update test item (to get back newly created one)
updateTest();
}).error(function(data, status) {
});
}
};
// first test items update
updateTest();
});

Ajax, json in AngularJS

I am trying to use the $http.get API to get a json data and then use it in my HTML tags.
I seem to miss something in the concept. here is my javascript:
var CouponsApp = angular.module('CouponsController', []);
CouponsApp.controller("CellCouponController", function($scope, $http){
$http.get('CouponsJSON.json').
success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
Here is my HTML:
<div id="CellTable" ng-controller="CouponController">
<p> Cell Phones Coupons</p>
<table border=1>
<tr>
<th>Model</th>
<th>Manufacturer</th>
<th>Cell Image</th>
<th>Manufacturer Url</th>
<th>Local Vendor</th>
<th>Local Vendor Address</th>
</tr>
<tr ng-repeat="coupon in coupons">
<td>{{CellPhones.model}}</td>
<td>{{CellPhones.manufacturer}}</td>
<td>
<img src="{{CellPhones.CellImage}}" alt="{{CellPhones.CellPhones}}" width="50px;" height="50px;" width="60px">
</td>
<td>
{{CellPhones.manufacturer}} URL
</td>
<td>{{CellPhones.localVendor}}</td>
<td>{{CellPhones.localVendorAddress}}</td>
</tr>
</table>
</div>
What is the correct way to get the json data, insert it to an object and then parse it in the ng-repeat?
You must define a $scope.coupons = {}; in your controller , and then attach your get data to that like this :
controller:
$scope.coupons = {};
$http.get('CouponsJSON.json')
.success(function(data){
// first console.log(data) it to check getting data is correctly working :
console.log(data);
$scope.coupons.coupon = data;
// its good practice to always use a DOT!!
})
Now in your html you can use ng-repeat like this :
<div ng-repeat="coup in coupons.coupon">
{{coup}}
</div>

Categories

Resources