Passing Object in ng-repeat to another page to display its contents - html

I am working on a project using MySQL, Angular, Express, and Node. I have a list of objects in a ng-repeat and when I click a specific item I would like to pass the clicked object to another page and show the object's properties through angular.
Here is the code:
HTML:
<div class = "panel panel-info" ng-repeat="job in job">
<div class = "panel-heading clickable">
<h1 class = "panel-title">{{job.title}}</h1>
<span class = "pull-right"><i class = "glyphicon glyphicon-minus"></i></span>
</div>
<div class = "panel-body">
<!--This will soon be the place where the Students information is placed by NodeJS-->
<!--<p style = "text-decoration: underline"> Job Title <p>-->
<p> {{job.description}} </p>
<p> {{job.first_name}} {{job.last_name}}</p>
<p> {{job.location}} </p>
<br>
<div class="form-group">
<div class=" col-sm-15">
<button onclick="location.href='jobPage.html';" type="submit" class="btn btn-default btn-block">Apply</button>
</div>
</div>
</div>
</div>
Controller:
soopControllers.controller("landingController",
function ($scope, $http){
$scope.formData = {};
$http.get('/api/jobLanding')
.success(function(data){
$scope.job = data;
console.log(data);
})
.error(function(data){
console.log('Error: ' + data);
});
//I want this function to get the job and send it to another page
$scope.getJob = function(){
$http.post('/api/job', $scope.formData)
.success(function(data){
$scope.formData = {};
$scope.users = data;
//$location.redirect();
console.log(data);
})
.error(function(data){
console.log('Error: ' + data);
});
};
});

AngularJS applications work the same way as regular web sites when it comes to navigation. The difference is that instead of sending a request to the server to go to the new URL, the router intercepts the location change, and goes to a route. The controller (or the resolve function) of that route then gets what it needs to display.
So, what you need in your ng-repeat instead of your button is
<a ng-href="#/job/{{ job.id }}">Apply</a>
And you then need a route mapped to the path /job/:jobId.
In the controller of this route, you'll then do something like
$http.get('/api/job/' + $routeParams.jobId).then(function(response) {
$scope.job = response.data;
});

How about using ng-click on the repeated element and extract that element in your display/routed page.
<div ng-controller="plandingController"
class = "panel panel-info"
ng-repeat="job in job"
ng-click="value.val=job">
....
</div>
In jobPage.html
<div ng-controller="plandingController" ng-repeat="pickedjob in value.val">

Related

ng-click according to element ID

So I have a ng-repeat iterating through an array that contains the elements form an API. Through the ng-repeat , I print out the same number of div(s) containing the names of some properties as the number of property present in the API in different objects. Now the next step that I want is that when I click on any property Name div, another screen is opened up which has the details of the property ( details are then fetched from the API which I can do). What I am not able to do is how to use the ng-click that it goes to the details screen but according the property that is clicked. I know that somehow I need to pass the property ID in ng-click and lead it to a different screen. Can't figure out how. Kinda am new to Angularjs so can someone help?
<div ng-repeat="prop in propertyDetails" class="propertyCard"
ng-click="Something here which I cant figure out ">
<p class="propSummaryName">{{ prop.name }}</p>
<div>
Now when the divs are created for the different properties when I click on one of them a new screen comes and then I show there what I want to show for the property.
PS- for property ID : prop.id
Use can directly write function call.
<div ng-repeat="prop in propertyDetails" class="propertyCard"
ng-click="propDetails(prop.id)">
<p class="propSummaryName">{{ prop.name }}</p>
$scope.showDetails(propId) {
// do want ever you want to };
If you want to show property details on another screen then you can use
modal or routing.
hey it's Simple You can call the #scope function in the ng Click and inside the function call the reset service and then open the popup
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body ng-app="myApp" ng-controller="test">
<div ng-init="loadData()">
<div ng-repeat="prop in propertyDetails" class="propertyCard"
ng-click="openMyPopUp(prop)">
<p class="propSummaryName">{{ prop.name }}</p>
<div>
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
Name : {{popupData.name}}
Id : {{popupData.id}}
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('test', function($scope, $http) {
var popup = angular.element("#myModal");
//for hide model
popup.modal('hide');
var url = 'your-url.com/rest/api'
$scope.loadData = function(){
$http.get(url).then(function(res){
$scope.propertyDetails = res.data;
});
}
$scope.openMyPopUp= function(data) {
$http.get(url + '?id=' + data.id).then(function(res){
$scope.popupData = res.data;
});
//for show model
popup.modal('show');
}
});
</script>
If you need to rederct to another page mean you can do like this
var url = "http://" + $window.location.host + "/Account/Login";
$log.log(url);
$window.location.href = url;
inside this function

Delete item in the database using a simple button on angular 7

im trying to create a delete button on one side of a word that i get from the data base and i cant figure out how to do it
I already delete the word but i have to use a input form on the html and i have to write by hand the word i that i want to delete, but this is no god for user experience, so thats why im seeking that X button
this is my html
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Hashtags</h4>
<h6 class="card-subtitle">Hashtags <code> uno</code> agregar.</h6>
<div class="row button-group">
<div class="col-lg-2 col-md-4" *ngFor="let hash of getHashtag">
<form [formGroup]="form" (ngSubmit)="onDelet(form.value)">
<button class="ti-close" type="submit"></button >
<input type="text" formControlName="hashtag" > {{hash}} <br>
<p id="competitors" > {{hash}}</p>
</form>
</div>
</div>
</div>
</div>
<div class="card">
this is my componet file:
public onDelet(){
this._getHashtag.deleteHashtag(this.form.value.hashtag).subscribe(
result =>{
// console.log(result)
this._getHashtag.getHashtag().subscribe(
resultado =>{
this.getHashtag = resultado
this.getHashtag = this.getHashtag.result
// console.log("Resultado", this.getHashtag)
},
error => {
var mensajeError = <any>error;
}
);
}
)
}
this is my service component:
deleteHashtag(hastagdel:string){
let header = new Headers({"Content-Type":"application/json"})
return this._http.post(this.url + "/removeHashtags" ,{hashtags:[hastagdel]}, {withCredentials:true})
}
I'm pretty sure you want to use http.delete, not http.post in your service.
http.post adds something to the db,
http.delete removes something,
http.put modifies something, and
http.get retrieves something from the db.
There are other http options, but those are the main ones.

Fetching individual JSON data on reactJS

When I parse A JSON from my server to my react front end it works fine perfectly but when I add a parameter to display an individual item I get an error. How do I display individual JSON data on react JS. I get the JSON data from my rest server. My code looks like the following.
In order to get the JSON I use the following method.
state = {
isLoading: true,
groups: [],
};
async componentDidMount() {
const response = await fetch('/product/all/1');
const body = await response.json();
this.setState({ groups: body, isLoading: false });
}
This is how I call the array
{this.state.groups.map(group => <div className="col-sm-12 col-md-6 col-lg-4 p-b-50">
{/* Block2 */}
<div className="block2">
<div className="block2-img wrap-pic-w of-hidden pos-relative block2-labelnew">
<img src={group.thumbnail} />
<div className="block2-overlay trans-0-4">
<a href="#" className="block2-btn-addwishlist hov-pointer trans-0-4">
<i className="icon-wishlist icon_heart_alt" aria-hidden="true" />
<i className="icon-wishlist icon_heart dis-none" aria-hidden="true" />
</a>
<button key={group.id} onClick={() => this.add(group.productid, group.name)} className="flex-c-m size1 bg4 bo-rad-23 hov1 s-text1 trans-0-4">Add to Cart</button>
</div>
</div>
<div className="block2-txt p-t-20">
<a href={`/productdetails/` + group.productid}>{group.name}</a>
</div>
</div>
</div>)}
I get an error saying "TypeError: this.state.groups.map is not a function"
My Spring backend to call all items and individual items look as the following
#GetMapping("/product")
public List<Product> index(){
return productRepository.findAll( );
}
#GetMapping("/product/all/{id}")
public Product show(#PathVariable String id){
int productId = Integer.parseInt(id);
return productRepository.findOne(productId);
}
P.S both api's seem working fine when tested on postman and fetching ("api/products") too works fine
this.state.groups.map is not a function . This means React expects this.state.groups to be an array. If you are returning only one item then do it like it this:
this.setState({ groups: [body], isLoading: false });
this way, body will be the first and only item in an array.

AngularJS $rootScope not accessible in html page

I have looked for the solution in following two links:
how-to-access-rootscope-value-defined-in-one-module-into-another-module
rootscope-variable-exists-but-not-accessible
But still could not find a solution.
I initialize $rootScope.user variable in $scope.login function, which is triggered by some other button click event, of my controller as:
app.controller('LoginFormController',['$rootScope','$location','$log','$scope','userAngService','userBean',function($rootScope,$location,$log,$scope,userAngService,userBean){
$scope.login = function(val){
$scope.user = userAngService.login(val).then(function(data){
$rootScope.user = data;
$location.path("/home");
});
};
}]);
Redirecting it to /home mapped in app.js as:
angular.module('Writer', ['AllControllers','ngRoute'])
.config(['$routeProvider', function($routeProvider,$Log){
$routeProvider.when('/Diary',{
templateUrl:'login.html',
controller: 'LoginFormController'
})
.when('/home',{
templateUrl: 'home.html',
controller: 'ReachController'
})
.otherwise({redirectTo : '/Diary'});
}]);
Now I am accessing $rootScope.user variable in the mapped controller ReachController as:
app.controller('ReachController',['$scope','$rootScope',function($scope,$rootScope){
$scope.user = {};
$scope.user = $rootScope.user;
console.log($scope.user);
}]);
It is perfectly logging angular object in console but is not avaiable in my home.html page.
Here is the html page - accessing it in <h2> and <h3> tags:
<div>
<h2>{{$scope.user}}hhhello</h2>
<h3>{{$scope.user.author}}</h3>
<div id="welcomeStory">
<span id="wsTitleBub">Title</span>
<input id="wsTitle" type="text" ng-model="wsPublish.welcomeStoryTitle" />{{wsPublish.welcomeStoryTitle}}
<h6>Words..</h6>
<textarea id="wsWords" ng-model="wsPublish.welcomeStoryWords"></textarea>
<input id="wsPublish" type="button" name="wsPublish" value="Publish" ng-click="pub = !pub" />
<input id="wsAddShelf" type="button" name="wsAddToShelf" value="Add To Shelf" ng-click="addToShelf()" />
</div>
<div id="wsPublishTo" ng-show="pub">
<ul>
<li>
<input type=submit id="wsgroups" value="Group" ng-click="publishGroup(wsPublish)" />
</li>
<li>
<button id="wsPublic" ng-click="public()">Public</button>
</li>
</ul>
</div>
</div>
Just change your $scope.user to user in your markup and it'll work.
Once it is in $rootScope you can directly access it in markup with {{user}} no need to again assign it to scope variable!

How do I update the model on click only (angular-strap typeahead and json)

I'm having trouble figuring out how to have dynamic data only update when the user selects from the typeahead menu or clicks the search button.
Right now, the dynamic content pertaining to the search query updates automatically when the input value is changed (content disappears). I want the content to stay in view until a new selection has been either clicked in the typeahead list or clicked by the search button.
Any insight at all would be greatly appreciated! Thank you!
Plunker demo:
http://plnkr.co/edit/jVmHwIwJ0KOKCnX6QjVa?p=preview
Code:
<!-- HTML -->
<body ng-controller="MainController">
<!-- Search -->
<div class="well">
<p>Search the term "content"</p>
<form role="form">
<div class="form-group clearfix search">
<input type="text" ng-model="selectedContent" ng-options="query as query.searchQuery for query in searchData" bs-typeahead="bs-typeahead" class="form-control search-field"/>
<button type="button" class="btn btn-primary search-btn"><span class="glyphicon glyphicon-search"></span></button>
</div>
</form>
</div>
<!-- Dynamic Content -->
<div class="well">
<h4>{{ selectedContent.contentTitle }}</h4>
<ul>
<li ng-repeat="item in selectedContent.headlines">{{item.headline}}</li>
</ul>
</div>
<!-- typeahead template -->
<ul class="typeahead dropdown-menu" tabindex="-1" ng-show="$isVisible()" role="select">
<li role="presentation" ng-repeat="match in $matches" ng-class="{active: $index == $activeIndex}">
</li>
<!-- JS -->
var app = angular.module('demoApp', ['ngAnimate', 'ngSanitize', 'mgcrea.ngStrap'])
.config(function ($typeaheadProvider) {
angular.extend($typeaheadProvider.defaults, {
template: 'ngstrapTypeahead.html',
container: 'body'
});
});
function MainController($scope, $templateCache, $http) {
$scope.selectedContent = '';
$http.get('searchData.json').then(function(response){
$scope.searchData = response.data;
return $scope.searchData;
});
};
You could use a directive such as this:
app.directive('mySearch', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, $element, $attrs, ngModel){
ngModel.$render = function(){
if (angular.isObject($scope.selectedContent)) {
$scope.clickedContent = $scope.selectedContent;
}
}
$scope.updateModel = function() {
$scope.clickedContent = $scope.selectedContent;
}
}
}
})
plunker
Edit:
I added using the ngModelController. The function you set ngModel.$render to gets called whenever the model updates. If you click the typahead popup, then the model selectedContent will be an object, otherwise it'll be a string. If it's an object (meaning the user clicked the typahead popup) we do the same as we did in the updateModel function.