How to show value on ng-click event? - angularjs

I am bit new to AngularJs and looking for help on some basic concepts.
Basically the following code correctly shows data returned from request API.
Request.cshtml
<div data-ng-controller="PostsController">
<strong class="error">{{ error }}</strong>
<strong data-ng-show="loading">loading..</strong>
<div data-ng-repeat="request in posts | orderBy: 'Id':true">
<strong>ID: {{ request.Id }}</strong>
<strong>Contact No: {{ request.ContactNumber }}</strong>
</div>
</div>
now i am further looking to add button in view and when user click on in, the contact number should be displayed.
i have written following html/angular view code.
show number
I need help in writing the corresponding "ShowNumber()" function in PostsController.js file.
But i am confused how to send single value instead of lists. Any help on it please?
here is my current PostsController.js code
function PostsController($scope, $http) {
$scope.loading = true;
$scope.editMode = false;
$http.get('/api/request').success(function (data) {
$scope.posts = data;
$scope.loading = false;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
}

The function:
$scope.ShowNumber=function(value){
//Your logic
}
HTML
<input type="button" value="Show" ng-click="ShowNumber(request.Id)" />
You can send any value in the function.
Also you can send a index of list:
ng-click="ShowNumber($index)"

Related

Updating a scope property doesn't update the view [duplicate]

This question already has an answer here:
ng-show="true" but still has class="ng-hide"
(1 answer)
Closed 4 years ago.
This is a question I've seen been asked many times before but I can't seem to find a solution that works for me. I have a simple code that updates a loading property and two divs, one that's supposed to be shown when loading is true and one that's shown when loading is false.
$scope.loading = true;
function getTasks() {
$http.get(URL)
.then(function (response) {
//success
$scope.tasks = response.data;
}
, function () {
//failure
$scope.errorMessage = "Failed to fetch tasks";
$timeout(getTasks(), 5000);
})
.finally(function () {
$scope.loading = false;
});
}
The HTML is as follows:
<div ng-show="{{ loading === true }}">
<i class="fa fa-spinner fa-w-16 fa-spin fa-lg"></i>
</div>
<div ng-show="{{ loading === false }}">
However, even though loading does change to false, it doesn't update the view.
Some of the things I've tried are:
Using the timeout service
$timeout(() => {
$scope.loading = false;
});
Using $scope.$apply() both after changing loading to false and calling a function inside of apply.
Adding the getTasks function to the scope.
<div ng-show="{{ loading === true }}"> should be <div ng-show="loading === true"> or just
<div ng-show="loading">
loading is a variable defined in your scope. And you can access scope variables as it is in your angular directives ng-show in your case

how to Dynamically Active tab with content for ui bootstrap tabs in angularjs?

I want to dynamically active tab with content in angular js
my code is
<uib-tabset ng-if="pets_count > 0" class="petsTabs tab-animation">
<div ng-repeat="(key, pet) in pets_list">
<uib-tab heading="{{pet.pet_name}}" active="{{pet.pet_id == activePet}}">
<div class="petsTabsContent" >
<h4>
{{pet.pet_name}}
<small>
Boarding Dates: {{ pet.start_date | date : 'MMMM d, y'}} to {{ pet.end_date | date : 'MMMM d, y'}}
</small>
</h4>
</div>
</uib-tab>
</div>
</uib-tabset>
i have two variables pet.pet_id, activePet on base for these variables i have to active tab.
but it does not working i am new to angular js
thanks in advance
This controller
$scope.show_pet_function = function () {
var pet_id;
var action;
pet_id = parseInt($('.pet_view_option').attr('data-pet_id'));
action = $('.pet_view_option').attr('data-action');
petowner_user_id = parseInt($('.pet_view_option').attr('data-pet-owner'));
var details = $scope.hidePetData;
$http.post(CONFIG.APIURL + 'Pets/changePetHideStatus/', {pet_id: pet_id, action: action})
.then(function (response) {
if (response.data.action == 'show_pet') {
promise = petlistFunction(petowner_user_id).then(function (response) {
$scope.activePet = pet_id;
angular.extend($scope.pets_list, response.data['pets_list']);
});
toastr.success(response.data.message);
} else if (response.data.action == 'hide_pet') {
promise = petlistFunction(petowner_user_id).then(function (response) {
$scope.activePet = pet_id;
angular.extend($scope.pets_list, response.data['pets_list']);
});
}
});
}
This is response for pet_list object type array
I think there might be an issue with $scope binding, as you are pulling the data in then-able function.
So try by placing $scope.$apply() after the $http response.
For reference add it like this
angular.extend($scope.pets_list, response.data['pets_list']);
$scope.$apply();

angular deleting a row in a table

I'm trying to delete a row in a table generated using angular ng-repeat directive and I get a "DELETE http://localhost:3000/api/delbike 404 (Not Found)" error. I suspect this to be an issue at the server end, but I'm also not getting the parameter to be passed to the $http service on angular end. Any help will be greatly appreciated. I expect $scope.bikes[idx] to pass the bike object selected for deletion. however while debugging it shows as undefined.Below is the angular code
//controller
ub.controller('bikectrl',["$scope","fbauthFact","$log","bike",function($scope,fbauthFact,$log,bike){
$log.log("In bike controller");
$scope.msg = "";
$scope.bikes =[];//bikes array to store bikes retrieved for a user
$scope.bike ={};//bike object to submit details of bike
//var bike ={};
var idx;
$scope.usr = fbauthFact.getResponseobj();
bike.getbikes($scope.usr).then(function(response){
$scope.bikes = response;
},function(reason){
$scope.msg = reason;
});//getbikes
$scope.delbike = function(idx){
$scope.bikes.splice(idx,1);
bike.delbike($scope.bikes[idx]).then(function(response){
$scope.msg = response;
},function(reason){
$scope.msg = reason;
});
};
}]);
//factory
ub.service('bike',['$http','fbauthFact','$log','$q',function($http,fbauthFact,$log,$q){
var user={};
var bike={};
//retrieve bikes
this.getbikes = function(user){
var deferred = $q.defer();
$http({
method:"GET",
url:"http://localhost:3000/api/getbike",
params: user
}).then(function successCallback(srresponse){
deferred.resolve(srresponse.data);
},
function failureCallback(srresponse){
$log.error("get bikes http call failed ",srresponse.data);
deferred.reject(srresponse.data);
});//$http
return deferred.promise;
};//getbikes
//delete bike
this.delbike = function(bike){
var deferred = $q.defer();
$http({
method:"DELETE",
url:"http://localhost:3000/api/delbike",
params: bike
}).then(function successCallback(srresponse){
deferred.resolve(srresponse.data);
},function failureCallback(srresponse){
deferred.reject(srresponse.data);
});
return deferred.promise;
};//delbike
}]);
//html
<div>
<div class='container' style='margin-top:90px;'>
<div class='row'>
<div class='col-md-8'>
<h3>Bikes of {{usr.first_name}}. Click here to add</h3>
</div>
</div>
</div>
<div class='container'>
<div class='table-responsive'>
<table class='table table-hover'>
<thead>
<tr>
<th>#</th>
<th>Make</th>
<th>Regno</th>
<th>Model</th>
<th>Year</th>
<th>Delete?</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in bikes">
<td>{{$index+1}}</td>
<td>{{x.brand}}</td>
<td>{{x.regno}}</td>
<td>{{x.model}}</td>
<td>{{x.year}}</td>
<td>
<button type="button" ng-click="delbike($index)" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</td>
</tr>
</tbody>
</table>
</table>
</div>
</div>
//server side snippet
app.delete('/api/delbike/*',function(req,res){
ubBike.remove({regno:req.query.regno},function(err,results){
if(err) throw err;
if(results.result.n==0)
{
res.send('Bike not registered');
}
else
{
res.send('Success');
}
});
});
Not sure about the first case of getting 404 not found
http://localhost:3000/api/delbike
It might be the server side issue or something buggy
but for the second case:
It will be undefined as you're removing it using this
$scope.bikes.splice(idx,1);
Before sending it to service for further processing
Try writting above block inside the resolver of the delete call
So you delbike method inside controller will look like following
$scope.delbike = function(idx){
bike.delbike($scope.bikes[idx]).then(function(response){
$scope.msg = response;
$scope.bikes.splice(idx,1); // add it here
},function(reason){
$scope.msg = reason;
});
};
Please checkout is your server side method type is HTTPDELETE or POST?
If it is POST Method then you need to change your Method type on your HTTP call
change method:"POST", it instead of method:"DELETE",
Also you don't need $scope.bikes.splice(idx,1); delete the object in the array, because the server also return deleted results.
I was able to resolve the issue by removing the slash '/' a the end of the router url in the api
app.delete('/api/delbike*',function(req,res){..

dynamically updating contents from the results of the cloud api using angular js

i am using angular js, bootstrap thumbnail and google cloud endpoints for my app.
The .html looks part looks like:
<body ng-controller="SearchController as searchCtrl">
<div class="row">
<div class="col-sm-2 col-md-2" ng-repeat="result in searchCtrl.searchResults">
<div class="thumbnail">
<img ng-src="{{result.thumbnailUrl}}">
</div>
</div>
</div>
The .js looks like below
(function(){
var app = angular.module('InstaMonitorAdmin', []);
app.controller('SearchController', function(){
this.searchResults = {};
this.searchTags = function(keyword){
//this.searchResults = results;
gapi.client.instagramApi.searchTags({'keyword':keyword}).execute(function(resp) {
if(resp && resp.hasOwnProperty('error')) {
// error
alert(resp.error.message);
}else{
var myJsonString = JSON.stringify(resp.items);
this.searchResults = myJsonString;
console.log(myJsonString);
}
});
};
});
In the console debugger it shows data for myJsonString as:
{"userName":"vikceo",
"caption":"#sandsculpture #sandcastle",
"tags":"[mountains, breathtaking, love, skyporn, minion]",
"thumbnailUrl":"https://scontent.cdninstagram.com/t51.2885-15/s150x150/e35/13108860_653673808116072_1235622514_n.jpg",
"kind":"instagramApi#resourcesItem"},
{"userName":"neetipari","caption":"My love #passion",
"tags":"[weddingcake, love, fondantcakes, foodporn]",
"thumbnailUrl":"https://scontent.cdninstagram.com/t51.2885-15/s150x150/e35/12940136_423862367814317_252510398_n.jpg",
"kind":"instagramApi#resourcesItem”}]
The issue is that the page does not render the search results returned from the google end point. I have tested that it return the results fine.
if i comment it and uncomment the top line where i am passing a hard coded array then it works fine.
Is it because it takes more time for response to come and assign to array? I thought it will continue to listen to this array. Please advise
so the problem turned out to be how i assigned the returned results. this is the final method:
app.controller('SearchController', function(){
this.searchResults = {};
this.searchTags = function(keyword){
var data = this;
data.searchResults = [];
gapi.client.instagramApi.searchTags({'keyword':keyword}).execute(function(resp) {
if(resp && resp.hasOwnProperty('error')) {
// error
alert(resp.error.message);
}else{
//successful login
console.log(resp);
data.searchResults = resp.items;
}
});
};
To have a synchronous assignment to the array , you could wait for the execution such as:
gapi.client.instagramApi.searchTags({'keyword':keyword}).execute(function(resp)).then(function(ress) {
//console.log(ress.items);
this.searchResults = ress;
});
Just add an ng-if, if you add ng-if element creates after data is come
<div ng-if="searchCtrl.searchResults.length" class="col-sm-2 col-md-2" ng-repeat="result in searchCtrl.searchResults.items">
<div class="thumbnail">
<img ng-src="{{result.thumbnailUrl}}">
</div>
</div>

Angularjs: push data into array from resource query and show in ngRepeat

there is an array data retrieved from a restful API using $resource and i fetch it using query() method. so i create a new data and i want to push the data created into the fetched array from $resource which is shown in ngRepeat directive, but when i make the push function, it doesn't push and i wouldn't like to re-query the whole data again.
controller
self.submit = function(){ //This function is called when i submit data creation
var form = self.form;
form.user_id = Global.user.id;
// hide error message if it's shown
self.data.error.show = false;
// check if submition is already on request (for some reason it submit twice)
if(!self.status.request){
self.status.request = true;
$timeout(function(){
projects.save({data: form}, function(data){ //function called from $resource
console.log(data);
self.status.request = false;
// Resolve Error
if(data.error[1])
resolveError();
// merge data to list
else{
form.id = data.id;
mergeData(form);
self.closeDialog();
}
});
}, 1000)
}
// show error message
function resolveError(){
var error = self.data.error;
error.show = true;
}
// merge form data into list data
function mergeData(data){
self.query.push(data); //this doesn't seem to work
console.log(data, self.query); //log to see if data is in array
}
}
view
<md-card ng-repeat="project in projects.query | orderBy:'id':true">
<md-toolbar>
<div class="md-toolbar-tools">
<h2>{{project.Name}}</h2>
<span flex></span>
<h3>{{project.user_id}}</h3>
</div>
</md-toolbar>
<md-card-content>
<p>{{project.Description}}</p>
</md-card-content>
<div class="md-actions" layout="row" layout-align="end center">
<md-button ng-href="#/projects/{{project.id}}">View</md-button>
</div>
</md-card>
note: the data is saved on the database, and for now the only way to see it on the list is by refreshing the page
update: projects is the alias of ProjectsController

Resources