Passing data from ng-Dialog html to controller - javascript

have some trouble with ng-Dialog.
When i note ngDialog controller option, it works.
I can get $scope.descriptionText value from
<p>Description:</p>
<textarea ng-model="descriptionText"></textarea>
now i call dialog witout parametr controller
ngDialog.open({
template: 'views/pages/timesheet/template/newEventTemplate.html',
//controller:'newEventDialogCtrl',
scope: $scope,
...
and this value $scope.descriptionText is undefined.
Please help me return values of html element to my controler, or to controller scope.
Dialog call code:
$scope.createNewEventModalWindow = function(args)
{
$scope.setNewEventField('start', args.start.value);
$scope.setNewEventField('end', args.end.value);
ngDialog.open({
template: 'views/pages/timesheet/template/newEventTemplate.html',
//controller:'newEventDialogCtrl',
scope: $scope,
className: 'ngdialog-theme-default',
plain: false,
showClose: true,
closeByDocument: true,
closeByEscape: true,
appendTo: false,
disableAnimation: false,
overlay: false
}).closePromise.then(function(value)
{
console.log('Test msg');
console.log(value);
var newEvent = {
start: $scope.getNewEventField('start'),
end: $scope.getNewEventField('end'),
text: $scope.descriptionText,
userID: getCurrentUserID(),
projectID: $scope.selectedProject,
taskID: $scope.selectedTask
};
console.log('Event data to server');
console.log(newEvent);
/*
TimesheetFactory.createEvent(newEvent)
.success(function(data) {
$scope.events = data;
$scope.message('Event created');
console.log($scope.events);
})
.error(function(data) {
console.log('Error: ' + data);
});
*/
});
}
Html template for dialog:
<div class="ngdialog-message">
<h3>Create Event</h3>
<p>Project</p>
<select id='selectProject' ng-model= "selectedProject">
<option ng-repeat="project in projects" value="{{project.id}}">{{project.name}}</option>
</select>
<p>Task</p>
<select id='selectTask' ng-model="selectedTask">
<option ng-repeat="task in tasks" value="{{task.id}}">{{task.name}}</option>
</select>
<p>Time</p>
<input type="time" id="eventTime" name="input" ng-model="timeLentgh"/>
<p>Description:</p>
<textarea ng-model="descriptionText"></textarea>
</div>
<div class="ngdialog-buttons">
<button
type="button"
class="ngdialog-button ngdialog-button-secondary"
ng-click="closeThisDialog()"
>Cancel</button>
<button
type="button"
class="ngdialog-button ngdialog-button-primary"
ng-click="btnCreateEventClicked()"
>Create</button>
</div>

You can access dialog's scope this way:
value.$dialog.scope()
Where value - argument you get from closePromise.
In this cope you'll have descriptionText for example.
Plunker to check and play: http://plnkr.co/edit/nTNwAxyL1KGuvKGAeTmy?p=preview

Related

Angular Modal Text Boxes Not Getting Populated with ngModel

I have a table with TV show data on it. I populate the table with dir-paginate/ng-repeat and I can click a row to open a modal to be able to edit the show but the ng-model data is not loading on the text boxes within that modal.
<tr id='schedule_row' class='hover_click_cell' dir-paginate='tv_show in tv_shows | orderBy:sortType:sortReverse | itemsPerPage:10'>
<td class='center_text clickable_cell cell_width' ng-click='alter_show(tv_show)'>{{tv_show.show_name}}</td>
When clicked, it calls the function alter_show()
$scope.alter_show = function(show)
{
$scope.edit_show = show;
var modalInstance = $uibModal.open ({ animation: $controller.animationsEnabled,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'edit_tv_show.html',
controller: 'EditTvShowCtrl',
controllerAs: '$controller',
size: 'sm',
backdrop: 'static',
keyboard: false
});
modalInstance.result.then(function (action)
{
},
function () {
});
}
The data passed looks like this in JSON form:
{"watched":false,"id":1,"show_name":"The Walking Dead","season":1,"episode":1,"season_episode":"Season 1, Episode 1","$$hashKey":"object:4"}
I pass in the show details and set it to the $scope.edit_show object. The data being passed on is not empty but when the modal is opened, the text boxes aren't populated. These are the input boxes:
$scope.edit_show = {
show_name: '',
season: 0,
episode: 0,
watched: 0
};
<div class='form-group'>
<label for='show_name'>Show Name:</label>
<input type='text' class='form-control' id='edit_show_name' ng-model='edit_show.show_name'>
</div>
<div class='form-group'>
<label for='season'>Season:</label>
<input type='number' class='form-control' id='edit_season' ng-model='edit_show.season'>
</div>
How can I get this to populate the text box with the details from the row that has been clicked?
I've manage to figure it out using resolve for the modalInstance.
$scope.alter_show = function(show)
{
var modalInstance = $uibModal.open ({ animation: $controller.animationsEnabled,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'edit_tv_show.html',
controller: 'EditTvShowCtrl',
controllerAs: '$controller',
size: 'sm',
backdrop: 'static',
keyboard: false,
resolve: { tv_show : function() { return show; } }
});
modalInstance.result.then(function (action)
{
},
function () {
});
}
angular.module('ui.bootstrap').controller('EditTvShowCtrl', function ($uibModalInstance, $scope, tv_show)
{
var $controller = this;
$scope.edit = tv_show;
});

Angular ng-click cannot get value of ng-model

I am working with a form and I literally just want to get the value from an ng-model. the form looks like this:
<form name="comment_form" class="row" novalidate>
<div class="col col-80 content col-center">
<input class="new-comment-message" type="text" style="margin-left: 15px;" placeholder="Leave a comment..." ng-model="new_comment" required></input>
</div>
<div class="col col-20 button-container col-center">
<button class="button button-clear send" type="submit" ng-click="addComment()" ng-disabled="comment_form.$invalid">
Send
</button>
</div>
</form>
This is my whole controller. The end result is to post a comment to wordpress however With my form content returning undefined its a bit difficult. (P.S. its posting to wordpress and the comment is just saying 'undefined'):
.controller('EasternInnerCtrl', function ($http, $timeout, $scope, $ionicLoading, $stateParams, $ionicScrollDelegate, $cordovaSocialSharing, $ionicModal, Easternc, AuthService) {
$scope.eastc = Easternc.get($stateParams.eastcId);
$ionicModal.fromTemplateUrl('commenter.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal
})
$scope.openModal = function() {
$scope.modal.show()
}
$scope.closeModal = function() {
$scope.modal.hide();
};
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
$scope.addComment = function(){
$ionicLoading.show({
template: 'Submiting comment...'
});
console.log($scope.new_comment);
Easternc.submitComment($scope.eastc.id, $scope.new_comment).then(function(data){
if(data.status=="ok"){
var user = AuthService.getUser();
var comment = {
author: {name: user.data.username},
content: $scope.new_comment,
date: Date.now(),
user_gravatar : user.avatar,
id: data.comment_id
};
console.log($scope.new_comment);
/*$scope.eastc.comments.push(comment);
console.log(comment);
$scope.new_comment = "";
$scope.new_comment_id = data.comment_id;
$ionicLoading.hide();
$ionicScrollDelegate.scrollBottom(true);*/
}
});
};
$scope.sharePost = function(link){
console.log(link);
window.plugins.socialsharing.share('I just read this article on blah: ', null, null, url);
};
})
my console log is showing: undefined when I click send though?
I'm pretty sure the modal got an isolated scope. It means $scope.new_comment wont exists in your controller.
You should try this :
$scope.addComment = function(comment){
Easternc.submitComment($scope.eastc.id,comment).then(function(data){
console.log(comment);
});
};
with this in your html
<button class="button button-clear send" type="submit" ng-click="addComment(new_comment)" ng-disabled="comment_form.$invalid">
Send
</button>
Hope it helped.

Call 2 functions in single ng-click

I am calling two functions on ng-click. But it doesn't work. I am not sure why the Refresh1() is not called when I cross-checked through debugger.
HTML CODE
<div class="row" ng-controller="PublishManifestCtrl">
<div class="col-xs-12 col-md-12">
<div class="widget">
<div class="widget-header bordered-bottom bordered-themeprimary">
<i class="widget-icon fa fa-tasks themeprimary"></i>
<span class="widget-caption themeprimary">Manifest Status</span>
</div>
<div class="widget-body">
<form class="form-bordered" role="form">
<div class="form-group">
<label style="padding-left: 8px;">Manifest was last published to agents on <b>{{manifeststatus.manifestLastPublishedDate}}</b>.</label>
</div>
<div class="form-group">
<label style="padding-left: 8px;">Manifest was last updated by <b> {{manifeststatus.lastUpdatedByUser}} </b> on <b>{{manifeststatus.manifestLastedUpdatedDate}}</b>.</label>
</div>
<div class="form-group">
<div class="col-sm-offset-1">
**<button id="PublishButton" class="btn btn-default shiny " ng-disabled="manifeststatus.enablePublishButton" ng-click="Save(manifeststatus);Refresh1()">Publish</button>**
</div>
<br/>
<div id="statusDivPublish" ng-show="showstatus">
<alert type="{{alert.type}}">{{alert.msg}}</alert>
</div>
</div>
</form>
</div>
JSFILE
$scope.Save = function (data) {
debugger;
$http.post($rootScope.WebApiURL + '/updatemanifeststatus');
//$http.get({ url: $rootScope.WebApiURL + '/getmanifeststatus' });
$scope.manifeststatus = data;
$scope.showstatus = true;
$scope.alert = { type: 'success', msg: 'Published Successfully.' };
$(".statusDivPublish").show();
}
$scope.Refresh1 = function () {
//refresh
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
}
});
new code
$scope.Save = function (data) {
debugger;
$http.post($rootScope.WebApiURL + '/updatemanifeststatus');
//$http.get({ url: $rootScope.WebApiURL + '/getmanifeststatus' });
$scope.manifeststatus = data;
$scope.showstatus = true;
$scope.alert = { type: 'success', msg: 'Published Successfully.' };
$(".statusDivPublish").show();
$scope.Refresh1();
}
$scope.Refresh1 = function ($rootScope, $state, $stateParams) {
debugger;
return {
restrict: 'AC',
link: function (scope, el, attr) {
el.on('click', function () {
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
});
}
};
};
});
The first one updates and displays a successfull message, while the second function refreshes the page.
use this
$scope.Save = function (data) {
debugger;
$http.post($rootScope.WebApiURL + '/updatemanifeststatus');
//$http.get({ url: $rootScope.WebApiURL + '/getmanifeststatus' });
$scope.manifeststatus = data;
$scope.showstatus = true;
$scope.alert = { type: 'success', msg: 'Published Successfully.' };
$(".statusDivPublish").show();
$scope.refresh();
}
call refresh inside the first function and remove it from the ng-click.
Update
You have a different type of problem i had it too. you try to refresh a state inside a method, it's really difficult i solve that problem with this snippet
if($state.current.name == /*name of the current state*/) {
$state.go($state.current, {}, {reload: true});
$modalInstance.close();
}
else {
$modalInstance.close();
$state.go(/*name of the current state*/);
}
it's not difficult but it didn't behave like you have understand it.
UPDATE
taking your code
$scope.Refresh1 = function () {
//refresh
$state.go($state.current, {}, {reload: true});
}
What about calling refresh inside of save in $http handler ?
Like this:
$http.post($rootScope.WebApiURL + '/updatemanifeststatus')
.then(function(){
$scope.Refresh1();
});
Don't execute two function in one ng-click, instead add the Refresh1 call to the end of the Save call, like so.
HTML
<button id="PublishButton"
class="btn btn-default shiny "
ng-disabled="manifeststatus.enablePublishButton"
ng-click="Save(manifeststatus)">Publish</button>
JS
$scope.Save = function (data) {
debugger;
$http.post($rootScope.WebApiURL + '/updatemanifeststatus');
//$http.get({ url: $rootScope.WebApiURL + '/getmanifeststatus' });
$scope.manifeststatus = data;
$scope.showstatus = true;
$scope.alert = { type: 'success', msg: 'Published Successfully.' };
$(".statusDivPublish").show();
$scope.refresh();
}
Update
If you are using AngularJS V1.2.2 or higher, then using ui-router, the following should work to reload the data.
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
The shortest way to accomplish this though would be with:
$state.go($state.current, {}, {reload: true}); //second parameter is for $stateParams
Its also worth noting that none of these will actually reload the page. If you want to reload the state AND the page, there is no ui-routermethod for it. Do window.location.reload(true)
Update 2
If you are receiving:
$state is not defined at Scope.$scope.Refresh1
(publishmanifest.js:44) at Scope.$scope.Save (publishmanifest.js:37)
at $parseFunctionCall (angular.js:12345) at angular-touch.js:472 at
Scope.$eval (angular.js:14401) at Scope.$apply (angular.js:14500) at
HTMLButtonElement. (angular-touch.js:471) at
HTMLButtonElement.n.event.dispatch (jquery.min.js:3) at
HTMLButtonElement.r.handle (jquery.min.js:3)
You are not injecting the $state service in your controller. You must do this in order to use it.
//without annotation (inferred, not safe when minifying code)
function Controller($scope, $state) {...}
//inline annotation
module.controller('Controller', ['$scope','$state', function($scope, $state) {...}]);
//$inject property annotation
function Controller($scope, $state) {...}
Controller.$inject = ['$scope', '$state'];
Pick one of the methods above to setup your controller to use $state.
Just make a third function like:
function3(data) {
save(data);
refresh1();
}

Save form data inside ng-dialog modal

So I have a form inside an ng-dialog plugin for angular js. The contents of the ng-dialog is loaded from external html file. The problem is that when I try to save the data it is undefined. I suspect that I am missing updating the ng-model that I use, but it is not clear how to do it. I have looked to some similar examples, but it still does not work.I want to collect the data when the button inside the form is pressed, not when the dialog is closed, but when closed will do as well. Here is my code:
angular.app.js
myApp.controller('RequestController', function ($scope, $http, $location, $window, subtitleRequestService, $sce, subtitlesApiServiceUrl, helperService, ngDialog) {
$scope.string_identifier = helperService.getParameterByName("v");
$scope.availableSubtitles = null;
$scope.request = {
status: "pending",
status_reason: "",
status_reason_f: ""
};
var getAvailableSubtitles = function()
{
subtitleRequestService.getAvailableSubtitlesForRequest().then(
function (res) {
var subs = res.data.message;
$scope.availableSubtitles = subs;
},
function () {
alert('Error');
}
);
};
$scope.saveStatus = function()
{
var sts = ($scope.request.status_option === "accepted" ? $scope.request.status_reason : $scope.request.status_reason_f);
$http.post(subtitlesApiServiceUrl + "changeRequestStatus/request_id/" + $scope.string_identifier + "/status/" + $scope.request.status + "/status_reason/" + sts)
.success(function (data, status, headers, config) {
alert(data.message);
}).error(function (data, status, headers, config) {
alert(data);
});
};
$scope.changeStatus = function()
{
getAvailableSubtitles();
var dialogInstance = ngDialog.open({
//appendTo: window.parent.document.getElementsByTagName('body'),
template: "/templates/change-request-status.html",
scope: $scope,
controller: 'RequestController',
className: 'ngdialog-theme-default'
});
};
});
externalTeamplate.html
<div class="ngdialog-message" ng-controller="RequestController">
<h3>Schimbă status</h3>
<div class="form">
<form class="form" name="$scope.request">
<div class="row">
<label for="status_options">Status</label>
<select name="status_options" id="status_options" ng-model="request.status_option">
<option value="pending" selected="selected">În procesare</option>
<option value="accepted">accepted</option>
<option value="rejected">rejected</option>
<option value="deleted">deleted</option>
<option value="in_translation">in_translation</select>
</select>
</div>
<div class="row" ng-show="request.status_option !== 'accepted'">
<label for="status_reason">Reason:</label>
<input type="text" id="status_reason" size="35" maxlength="144" ng-model="request.status_reason" />
</div>
<div class="row" ng-show="request.status_option=='accepted'">
<label for="status_reason_f">Please select:</label>
<select id="status_reason_f" ng-repeat="(key, value) in availableSubtitles" ng-model="request.status_reason_f">
<option value="{{key}}">{{value}}</option>
</select>
</div>
</form>
</div>
</div>
<div class="ngdialog-buttons">
<button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="saveStatus()">Salvează</button>
</div>
What am I missing? Thanks!

AngularJS - Pass object data into modal

I have an information screen in which I'm using a repeater to build out information on a specific user.
When the "Edit" button is clicked, how can I pass the specific user object data into the modal window template?
HTML
<form class="custom" ng-controller="DepCtrl" ng-cloak class="ng-cloak">
<fieldset ng-repeat="object in data.dataset">
<legend><span>{{ object.header }}</span><span class="dep_rel">({{ object.relation }}) </span></legend>
<div class="row">
<div class="four columns" ng-repeat="o in object.collection.inputs">
<span class="table_label">{{ o.label }}:</span><span class="table_answer">{{ o.value }}</span><br>
</div>
</div>
<div class="row">
<a ng-click="openDialog('edit')" style="color:#444;text-decoration:none;margin-right:10px;margin-top:5px;" class="btn_gray smaller left" href="#">Edit</a>
<a style="color:#444;text-decoration:none;margin-top:5px;" class="btn_gray smaller" href="#">Delete</a>
</div>
</fieldset>
</form>
JS
function DepCtrl($scope, Dependents, $dialog) {
$scope.data = Dependents;
var t = '<div class="modal-header">'+
'<h3>' + $scope.header.value + '</h3>'+
'</div>'+
'<div class="modal-body">'+
'<p>Enter a value to pass to <code>close</code> as the result: <input ng-model="result" /></p>'+
'</div>'+
'<div class="modal-footer">'+
'<button ng-click="close(result)" class="btn btn-primary" >Close</button>'+
'</div>';
$scope.opts = {
backdrop: true,
keyboard: true,
dialogFade: true,
backdropClick: false,
template: t, // OR: templateUrl: 'path/to/view.html',
controller: 'TestDialogController'
};
$scope.openDialog = function(action){
var d = $dialog.dialog($scope.opts);
//if (action === 'edit') { $scope.opts.templateUrl = '../../modal.html'; }
d.open().then(function(result){
if(result)
{
alert('dialog closed with result: ' + result);
}
});
};
}
It helps to know which $dialog service you are referring to exactly, since $dialog is not the part of core AngularJS API.
Assuming that you are using the $dialog service from the ui-bootstrap, you can pass your user object into the dialog controller through the resolve property of $dialog configuration object.
As the $dialog documentation states it:
resolve: members that will be resolved and passed to the controller as
locals
function DepCtrl($scope, Dependents, $dialog) {
$scope.data = Dependents;
$scope.opts = {
backdrop: true,
keyboard: true,
dialogFade: true,
backdropClick: false,
template: t, // OR: templateUrl: 'path/to/view.html',
controller: 'TestDialogController',
resolve: {
user: function(){
return $scope.data;
}
}
};
$scope.openDialog = function(action){
var d = $dialog.dialog($scope.opts);
d.open();
};
}
/**
* [TextDialogController description]
* #param {object} $dialog instance
* #param {mixed} user User object from the resolve object
*/
function TextDialogController(dialog, user){
...
}

Categories