Angularjs passing id into modal function() - angularjs

I am using angularjs and spring mvc for my application. At first I am displaying all the placements with one button Placed Candidates. I am doing ng-repeat for displaying all the placements.
Here is my html.
<div class="row" data-ng-repeat="placement in placements">
<div class="col-xs-12 col-sm-12 col-md-12">
<h5>{{placement.companyName}}</h5>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<h6>{{placement.placementDate | date:'dd MMM yyyy'}}</h6>
Company Target (appox):10 Achieved:
</div>
<a href="javascript:void(0);" data-ng-
click="placedcandidatespopup(placement.placementId);">//here i can
get particular placementId but how to pass this id to
savePlacementStudents() method in controller.js???//
PlacedCandidates
</a>
</div>
I am calling one modal popup function. Here is controller.js
$scope.placedcandidatespopup = function()
{
AdminUsersService.getAllUsers().then(function(response)
{
$scope.allusers=response.data;
console.log($scope.allusers);
})
$(".placedcandidates").modal("show");
}
I am calling modal by name "placedcandidates".
Here is the modal
<div class="modal right fade placedcandidates" id="myModal1"
tabindex="-1" role="dialog" aria-labelledby="myModalLabel2">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6" data-ng-
repeat="student in allusers">
<input id="{{student.studentId}}" type="checkbox" value="
{{student.studentId}}" data-ng-
checked="selection.indexOf(student.studentId) >-1"
data-ng-click="toggleSelection(student.studentId)"/>
<label for="{{student.studentId}}"></label>
{{student.firstName}}
</div>
</div>
</div>
<div class="modal-footer" style="position: fixed;">
<input type="button" value="Submit" class="btn" data-ng-
click="savePlacementStudents()">
</div>
</div>
</div>
</div>
After clicking on button popup modal will display with all Students with checkboxes placed beside them.Now I am able to save studentId into database.But I am not able to pass placementId for saving.
Here is my savePlacementStudents method in controller.js.
$scope.selectedStudents = {};
$scope.savePlacementStudents = function(selectedStudents)
{
selectedStudents.selectedList = $scope.selection;
AdminPlacementService.savePlacementStudents(selectedStudents).then
(function(response)
{
if(response.data=="success"){
$window.scrollTo(0,0);
$scope.selectedStudents = {};
$scope.getplacementdetails($scope.currentPageIndex);
$scope.successmessage="Student Selection Saved!;
$timeout(function() {
$scope.successmessage="";
$scope.closeplacedcandidatespopup();
}, 1500);
}
});
}
Can anyone tell how can I pass respective placementId to this saveStudents method() so that I can set that placementId for those students selected.

Here is the solution.
The placementId passed to function placedcandidatespopup can be saved as follows in function placedcandidatespopup
$scope.selectedPlacementId = placementId;
Now the same $scope will have access in Popup also as it is using same controller.js. And now you can use this $scope.selectedPlacementId anywhere in controller.js
So you don't need to pass placementId...!!
Hope that would help you..!!

$scope.placedcandidatespopup = function(id)
{
AdminUsersService.getAllUsers().then(function(response)
{
$scope.allusers=response.data;
console.log($scope.allusers);
})
$scope.inserted = {
placementId:id,
};
var modalInstance = $uibModal.open({
templateUrl: 'views/test/myModal1.html',
controller: 'TestCntrl',
size: "Modelwidth",
resolve: {
items: function () {
return $scope.inserted;
}
}
});
}
In model you have to access using items.placementId and when you savePlacementStudents() method send placementId as well with student info.

Related

Update view when api get data in Angularjs

So, i have a little problem. I made a tiny webapp that uses the omdb api. The thing is this that when i type in the movie that i'm searching for then press the search button, the view should change to the result.html view and show the data i got from the api.
The api works fine. I got the data to display, but that was in my index.html. Now i have splitted the files by using ng-routes
I can provide you the whole project if you wanna look at it. Maybe i can upload it to a online editor somewhere?
This is my app.js
var myApp = angular.module("myApp", ['ngRoute']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'views/home.html',
controller: 'filmController'
}).
when('/result', {
templateUrl: 'views/result.html',
controller: 'filmController'
}).otherwise({
redirectTo: '/home'
})
}]);
myApp.controller("filmController", function filmController($scope, $http, $window) {
$scope.getData = function () {
var movieTitle = document.getElementById("filmName").value;
var binding = document.getElementsByClassName("ng-binding");
$http
.get("http://www.omdbapi.com/?t=" + movieTitle + "&apikey=526345a6")
.then(function (response) {
var data = response.data;
if (data.Error) {
alert("Film inte funnen");
return false;
}
for (let key in data) {
if (data.hasOwnProperty(key)) {
let element = data[key];
if (element === "N/A") {
data[key] = "Inget hittat";
if (key === "Poster") {
$scope.post = "Ingen poster hittad";
}
}
$scope.url = data;
}
}
if (data.Ratings.length === 0) {
$scope.rate = "Ingen utmärkelse/er hittad";
}
// This api data is printed to the console on the index.html view, i want it in the result view...
console.log(data);
});
};
});
This is my index.html
<body>
<div class="main-content">
<!-- <div class="container">
<div class="row">
<div ng-controller="MyController">
<div ng-repeat="item in larare" class="col-lg-12">
<div class="card">
<img ng-src="/images/{{item.shortname}}.jpg" alt="Bild på {{item.name}}" class="card-img-top">
<div class="card-body">
<h3 class="card-title">{{item.name}}</h3>
<p class="card-text">{{item.reknown}}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div> -->
<header ng-include="'header.html'"></header>
<main ng-view></main>
</div>
</div>
<script>
var elem = document.getElementsByTagName("body")[0];
if (elem.requestFullscreen) {
elem.requestFullscreen();
console.log("Nu");
} else {
console.log("Error");
}
function updateSite(event) {
window.applicationCache.swapCache();
}
window.applicationCache.addEventListener('updateready',
updateSite, false);
</script>
<script src="./js/formvalidation.js"></script>
</body>
</htm>
And my result view
<div class="show container" ng-show="url.Title">
<div class="poster">
<!-- <img ng-src="{{ url.Poster }}" alt="" /> -->
<img ng-src="{{ url.Poster == 'Inget hittat' ? './images/image_not_found.png' : url.Poster }}">
<p class="text-dark">{{ post }}</p>
</div>
<h2 class="text-dark">{{ url.Title | uppercase}}</h2>
<div class="movie-info">
<p class="text-dark">
<strong>Från:</strong> {{ url.Year }}</p>
<p class="text-dark">
<strong>Rating:</strong> {{ url.Rated }}</p>
<p class="text-dark">
<strong>Utgiven:</strong> {{ url.Released }}</p>
<p class="text-dark">
<strong>Längd:</strong> {{ url.Runtime }}</p>
</div>
<p class="text-dark">
<strong>Skådespelare:</strong> {{ url.Actors }}</p>
<p class="text-dark">
<strong>Regissör:</strong> {{ url.Director }}</p>
<p class="text-dark">
<strong>Utmärkelser:</strong> {{ url.Awards }}</p>
<p class="text-dark">
<strong>Handling: </strong> {{ url.Plot }}</p>
<h4 class="text-dark">
<strong>Utmärkelser</strong>
</h4>
<p class="text-dark ">{{ rate }}</p>
<div ng-repeat="rating in url.Ratings | orderBy: '-Value'">
<p class="text-dark">
<strong>{{ rating.Source + ': ' + rating.Value }}</strong>
</p>
</div>
This is my home view
<section class="text-white">
<img src="./images/background.jpg" alt="Bild på poster från Frankenstein filmen" class="bg-image">
<div class="main container align-middle">
<div class="row text-center justify-content-center section-intro">
<div class="col-6 mb-5">
<h1>Filmtipset</h1>
<h5>Sök efter dina favortfilmer</h5>
</div>
</div>
<form ng-submit="getData()">
<div class="inputSearch mx-auto">
<div class="row justify-content-center">
<div class="col-8">
<div class="form-group">
<label for="filmName">Film</label>
<input class="form-control" type="text" name="filmName" id="filmName" placeholder="Ex. Armageddon" autofocus>
</div>
<input type="submit" class="btn btn-primary btn-lg btn-block btn-info mt-5" onclick="validateForm()" ng-click="'#!/result'">
</div>
</div>
</form>
Just a few notes before we break down the issue you are seeing. It seems like you aren't using angularjs to its full potential. Using a mixture of jquery and angularjs is not best practice and can make debugging very difficult. I would recommend making movieTitle an ng-model, as well as using angularjs's built in form validation. This will allow you to access the movieTitle easily in your controller as well as take advantage of angular's built in form controller and actions.
As for getting the data to your other page, I would add a second controller for that page, then from your filmController, you can pass the movie title as a route param when changing views. In your resultController, you can get the movie title from the route param and then do your api call while initializing the result page/controller.
In your home.html file, we will add ng-model to the input to be more angularjs friendly. Now we can access movieTitle in the controller with $scope.movieTitle. I am also changing the method that should get run on submit to the search() method I have added to the filmController.
home.html
<form ng-submit="search()">
// ... your other html here
<input class="form-control" type="text" name="filmName" id="filmName" ng-model="movieTitle" placeholder="Ex. Armageddon" autofocus>
In your filmController, I would add $location and move the getData() method to a resultController. We will now call search() on form submit, then use $location to switch views to your result view, attaching the movie title as a route param so we can access it in the resultController.
filmController.js
myApp.controller("filmController", function filmController($scope, $http, $location) {
// ... other code you have
// this will be what gets called after the user types a movie title
$scope.search = function () {
var title = $scope.movieTitle; // or using jquery(not recommended)
// this will change location and will produce
// the url: http://[yoursite]/result?movieTitle=title
$location.path('/result').search({movieTitle: title});
}
});
In your newly created resultController, we will get that route param and use it to search for the data.
resultController.js
myApp.controller("resultController", function resultController($scope, $http, $routeParams) {
// the getData method moved to this controller
$scope.getData = function (movieTitle) {
$http
.get("http://www.omdbapi.com/?t=" + movieTitle + "&apikey=526345a6")
// the rest of your code for getData here
};
// I like to make an init method to make it clear what we are initializing
$scope.init = function () {
// this will get the movieTitle from the /result?movieTitle=title part of your url
var movieTitle = $routeParams['movieTitle'];
// now we call the method you have that uses the omdb api
// just modify it to accept the movie title as a param rather than finding it in the html
$scope.getData(movieTitle);
}
// run init method
$scope.init();
});
Finally, you will want to update your app config to have your result route use the resultController we added instead of the filmController.

Controller doesn't get parent data

I'm doing a tutorial over angular 1.5 and I've gotten far into it and one of the sections seems broken concerning matching a current user to the author username. The class injects the User service and I think assumes I can inherit from a parent controller for the author but it comes up undefined. I tried injecting $scope then setting a variable to $scope.$parent.article (article is the object that has the author name in it) but this was still undefined. I checked the parent controller doing a console log on article and it does have the data that I am trying to get. Here is a link to my project if you want to look at the entire thing but I'll try to post just the relevant code below. https://github.com/RawleJuglal/flow_news_app/tree/front_end/src/js
Parent Controller (article.controller.js)
import marked from 'marked';
class ArticleCtrl {
constructor(article, $sce, $rootScope) {
'ngInject';
this.article = article;
console.log(this.article);
//THIS IS CONSOLE LOG
//{title: "Juglal For StackOverflow",
slug: "juglal-for-stackoverflow-ba400n",
body: "<p> Need the goods</p>",
createdAt: "2017-04-25T14:51:42.131Z",
updatedAt: "2017-04-25T14:51:42.131Z",
author:{
bio:"I'm a MEAN stack developer. But if I don't find a job in Oklahoma soon, I'll be learning C++/Sharp."
following:false
image:"https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/6/000/1e9/0e2/3cd7175.jpg"
username:"RawleJuglal",....
}
// Update the title of this page
$rootScope.setPageTitle(this.article.title);
this.article.body = $sce.trustAsHtml(marked(this.article.body, { sanitize: true }));
}
}
export default ArticleCtrl;
Child Controller (article-actions.components.js)
class ArticleActionsCtrl {
constructor(Articles, User, $state) {
'ngInject';
this._Articles = Articles;
this._$state = $state;
//Code that causes the error because this.article.author.username is undefined
if (User.current) {
this.canModify = (User.current.username === this.article.author.username);
} else {
this.canModify = false;
}
}
}
let ArticleActions = {
bindings: {
article: '='
},
controller: ArticleActionsCtrl,
templateUrl: 'article/article-actions.html'
};
export default ArticleActions;
HTML(article.html) //Just in case this the problem
<div class="article-page">
<div class="banner">
<div class="container">
<h1 ng-bind="::$ctrl.article.title"></h1>
<article-actions article="$ctrl.article"></article-actions>
</div>
</div>
<div class="container page">
<div class="row article-content">
<div class="col-xs-12">
<div>
<div ng-bind-html="::$ctrl.article.body"></div>
</div>
<ul class="tag-list">
<li class="tag-default tag-pill tag-outline"
ng-repeat="tag in ::$ctrl.article.tagList">
{{ tag }}
</li>
</ul>
</div>
</div>
<hr />
<div class="article-actions">
<article-actions article="$ctrl.article"></article-actions>
</div>
<div class="row">
<div class="col-xs-12 col-md-8 offset-md-2">
<div>
<form class="card comment-form">
<div class="card-block">
<textarea class="form-control"
placeholder="Write a comment..."
rows="3"></textarea>
</div>
<div class="card-footer">
<img class="comment-author-img" />
<button class="btn btn-sm btn-primary" type="submit">
Post Comment
</button>
</div>
</form>
</div>
<div class="card">
<div class="card-block">
<p class="card-text">This is an example comment.</p>
</div>
<div class="card-footer">
<a class="comment-author" href="">
<img class="comment-author-img" />
</a>
<a class="comment-author" href="">
BradGreen
</a>
<span class="date-posted">
Jan 20, 2016
</span>
</div>
</div>
</div>
</div>
</div>
</div>
In fact, your example will work with angular 1.5 but not >1.6.
here is the reason :
Starting with angular 1.6, bindings are not yet set in the constructor. If you need them, move your code to the $onInit function.
Here is your new ArticleActionsCtrl :
class ArticleActionsCtrl {
constructor(Articles, User, $state) {
'ngInject';
this._Articles = Articles;
this._$state = $state;
this.User = User;
}
$onInit() {
if (this.User.current) {
this.canModify = (this.User.current.username === this.article.author.username);
} else {
this.canModify = false;
}
}
}
let ArticleActions = {
bindings: {
article: '='
},
controller: ArticleActionsCtrl,
templateUrl: 'article/article-actions.html'
};
export default ArticleActions;
I did not test it, do not hesitate to tell me if you have any problem with it.

`ng-click` not calling the controller function some times

I have 2 popup's which is controller by a service in a page. on click on the div element i am calling the controller function. after i added the 2nd popup directive especially some times the ng-click not working properly. how to solve this?
here is my service.js
"use strict";
angular.module("tcpApp").service("modalService", function ( $rootScope) {
//header configuration
$rootScope.hideModal = function() {
$rootScope.showModal = false;
};
this.changePass = function ( configId ) {
$rootScope.showModal = true; //this is for global
$rootScope.currentConfigPopView = 'views/tools/'+configId+'.html';
$rootScope.$apply();
};
this.showSummary = function () {
this.showSummaryPop = true;
}
this.hideSummary = function () {
this.showSummaryPop = false; //this is within controller
}
});
html:
<div class="statusBoard board8" ng-click='modal.showSummary("board8")'>
<span><img src="../images/iconDetails.png" alt="icon plan and actual"></span>
<h2>{{boardAssets.board8.title}}</h2>
<span class="row dwo">
<span class="catg">Total Issue Reported</span>
<span class="cd issueData">{{contractor.IssueDetails.TotalIssue}}</span>
</span>
<span class="row mas">
<span class="catg">Issue Resolved</span>
<span class="cd resolveData">{{contractor.IssueDetails.IssueResolved}}</span>
</span>
<span class="row rfi">
<span class="catg">Issue Remaining</span>
<span class="cd remainData">{{contractor.IssueDetails.IssueRemaining}}</span>
</span>
</div>
<body-footer></body-footer>
<config-popup></config-popup> //after i added this directive getting ng-click issue.
<modal-popup></modal-popup>
config popup html:
<div class='ng-modal' ng-if="showModal">
<div class='ng-modal-overlay' ng-click='hideModal()'></div>
<div class='ng-modal-dialog' ng-style='dialogStyle'>
<div class='ng-modal-dialog-content'>
<ng-include src="currentConfigPopView"></ng-include>
</div>
</div>
</div>

angular does not load my directive

I newly start to use angular.but I have some problem to loading my directive.
I want to load my directive as soon as page loaded.
where I load data-show directive
<div class="row">
<div class="col-md-12">
<article class="row" ng-controller="DataCtrl">
<input type="button" ng-click="getDataList()" >
<h1>Some Content Here</h1>
<ul id="home" bread-crumbs></ul>
<ul class="thumbnails">
<li ng-repeat="data in list" class="col-md-5">
<show-data data="data"/>
</li>
</ul>
</article>
</div>
</div>
showData directive:
app.directive('showData', function () {
return{
restrict: 'E',
replace:true,
templateUrl: 'views/directives/datas.directive.html',
scope: {
data: "="
},
controller:'DataCtrl'
}
})
and template I used in:
<div class="well hoverwell">
<div class="row">
<h2 class="col-md-4">{{data.name}}</h2>
</div>
<div class="row">
<span class="col-md-1">Code:</span>
<span class="col-md-1">{{data.id}}</span>
</div>
<div class="row">
<span class="col-md-1">accountability:</span>
<span class="col-md-1">{{data.parent}}</span>
</div>
<div class="row">
<span class="col-md-1"> :</span>
<span class="col-md-1">{{data.definition}}</span>
</div>
</div>
and my controller
'use strict';
angular.module('app')
.controller('DataCtrl', function ($scope, DataService, $log) {
$scope.getDataList = function () {
var list = DataService.getDataList(1);
list.then(
function (result) {
$log.info(result);
$scope.dataList = result;
}, function (status) {
$log.error(status)
$scope.msg = "error " + status + " has been occur,please report to admin ";
});
};
});
and when I run my app it does not work .
when I watch it in chorome development tools my directive is comment
what is my problem.How can I call this directive as soon as page load.
thx
As you already noticed, you see empty list because your dataList in ng-repeat is not filled yet.
But you have some errors in your code:
First of all - you should never use one controller twice. So you need to create separate controller for your directive.
replace directive parameter is deprecated, better not to use it.
In your DataCtrl you set the dataList variable: $scope.dataList = result;, but in HTML you refer to list variable: <li ng-repeat="data in list" class="col-md-5">.
Maybe that example will help you to figure out with your code.

Convert user input into a label using angular.js

What I'am trying to do is convert every user input into a label using angular. I believe that I'am doing the right thing, but is not working. I will appreciate if somebody take a look at this code. Thank you
here is a plunker
<div class="row" ng-controller="tagForm">
<div ng-click="addEntry()">
<div class="col-xs-12 col-sm-12 col-md-10 ">
<input type="text" placeholder="What are your area of expertise" ng-model="newEntry.name" class="form-control border" />
</div>
<div class="col-xs-12 col-md-2 center form-button">
<input type="button" value="Add" class="btn btn-orange btn-add" />
</div>
<div class="col-md-8 col-sm-offset-2" id="up">
<br />
<span class="label label-primary" ng-repeat="entry in entries">{{entry.name}}</span>
</div>
</div>
</div>
app.controller('tagForm', ['$scope', function($scope) {
return $scope.addEntry = function() {
$scope.entries.push($scope.newEntry);
return $scope.newEntry = {};
};
}]);
You have a few things wrong in your Plunk, but here's some stuff to start with:
You need to wire up a click event on your Add button. Right now, its not doing anything when you click it
Bind to an ng-model on the scope just using 'newEntry'. All you're typing is a name so thats all you need to save on the scope.
Loop over entries, printing out just 'entry' instead of 'entry.name'
And your controller should look like this (no need for the returns)
app.controller('tagForm', ['$scope', function($scope) {
$scope.entries = [];
$scope.addEntry = function() {
$scope.entries.push($scope.newEntry);
};
}]);
See this fiddle:
http://jsfiddle.net/smaye81/anrv2qms/1/

Resources