returning data from angularjs modal dialog service - javascript

I am fairly new to AngularJS and having a problem with returning data from a modal dialog service. Basically, I copied Dan Wahlin's service http://weblogs.asp.net/dwahlin/archive/2013/09/18/building-an-angularjs-modal-service.aspx and am calling it from my controller.
myApp.controller('MyController', function($scope, ModalService) {
window.scope = $scope;
$scope.mydata = {name: ""};
$scope.showModal = function () {
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Save',
headerText: 'Save Dialog'
}
ModalService.showModal({}, modalOptions).then(function (result) {
});
}
});
Then I have my partial like so:
<div class="modal-header">
<h3>{{modalOptions.headerText}}</h3>
</div>
<form ng-submit="modalOptions.submit()">
<div class="modal-body">
<label>Name</label>
<input type="text" data-ng-model="mydata.name">
</div>
<div class="modal-footer">
<button type="button" class="btn" data-ng-click="modalOptions.close()">{{modalOptions.closeButtonText}}</button>
<button type="submit" class="btn btn-primary">{{modalOptions.actionButtonText}}</button>
</div>
This modal is being invoked like this:
<button class="btn btn-primary hidden pull-right" id="save" data-ng-click="showModal()">Save</button>
So my question is how do I get the value of the name field back to the controller? I've looked all over the web and all the examples have the function that opens the modal reside inside the controller, which makes it much easier as $scope from the controller also exists in the function that opens the modal.
I tried adding the following code to the 'show' function in the service but it did not work.
tempModalDefaults.resolve = function($scope) {
mydata = function () {
return $scope.mydata;
}
}
Thanks
P.S. I renamed modalService to ModalService in my code, so that's not a typo. The modal opens and closes as it should, I just can't pass the field's value back to the controller.

In your button, add data-ng-click="modalOptions.ok(mydata)"
<button type="submit" class="btn btn-primary" data-ng-click="modalOptions.ok(mydata)">{{modalOptions.actionButtonText}}</button>
And you can get it from:
ModalService.showModal({}, modalOptions).then(function (result) {
console.log(result.name);
});
DEMO
If you want to use modalOptions.submit function, you need to change your code a bit
In your HTML, pass the mydata to modalOptions.submit function:
<form ng-submit="modalOptions.submit(mydata)">
Your Model Service, replace in the show function:
return $modal.open(tempModalDefaults); //remove the .result
Your controller:
$scope.showModal = function () {
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Save',
headerText: 'Save Dialog',
submit:function(result){
$modalInstance.close(result);
}
}
var $modalInstance = ModalService.showModal({}, modalOptions);
$modalInstance.result.then(function (result) {
console.log(result.name);
});
}
DEMO

Related

Angular uibModal, Resolve, Unknown Provider

I am trying to expose a "generic" modal - using Angular's $uibModal - through a service. Here is the definition of that service:
angular.module('app').service('CustomModalService', ['$uibModal', function ($uibModal) {
var openCustomModal = function (size, title, message) {
var actionToPerformOnConfirm = action;
var modalInstance = $uibModal.open({
templateUrl : 'templates/CustomModal.html',
size: size,
resolve: {
title: title,
message: message
}
});
};
return {
openCustomModal: openCustomModal
};
}]);
Nothing too complicated, above. However, it is not working. If I remove the resolve property from the object, the service works; however, if I include the resolve property, I get the Unknown Provider error originating from that property.
The documentation for the resolve property reads:
(Type: Object) - Members that will be resolved and passed to the
controller as locals; it is equivalent of the resolve property in the
router.
The objective is to be able to provide a template for the modal that utilizes these properties in its DOM, e.g. :
<div ng-controller="CustomModalController">
<div class="modal-header">
<h3 class="modal-title">{{title}}</h3>
</div>
<div class="modal-body">
{{message}}
</div>
<div class="modal-footer">
<button class="ad-button ad-blue" type="button" ng-click="confirmAction()"></button>
<button class="ad-button ad-blue" type="button" ng-click="cancelAction()"></button>
</div>
</div>
What am I missing that is causing this error to be thrown?
You have two problems:
You need to define the controller in your modal config
Your resolve object needs to be a map of string: function, where string is the name of the dependency that will be injected into your modal's controller, and function is a factory function that will be used to provide that dependency when the controller is instantiated.
Working example: JSFiddle
JavaScript
angular.module('myApp', ['ui.bootstrap'])
.controller('MyModalController', MyModalController)
.directive('modalTrigger', modalTriggerDirective)
.factory('$myModal', myModalFactory)
;
function MyModalController($uibModalInstance, items) {
var vm = this;
vm.content = items;
vm.confirm = $uibModalInstance.close;
vm.cancel = $uibModalInstance.dismiss;
};
function modalTriggerDirective($myModal) {
function postLink(scope, iElement, iAttrs) {
function onClick() {
var size = scope.$eval(iAttrs.size) || 'lg'; // default to large size
var title = scope.$eval(iAttrs.title) || 'Default Title';
var message = scope.$eval(iAttrs.message) || 'Default Message';
$myModal.open(size, title, message);
}
iElement.on('click', onClick);
scope.$on('$destroy', function() {
iElement.off('click', onClick);
});
}
return {
link: postLink
};
}
function myModalFactory($uibModal) {
var open = function (size, title, message) {
return $uibModal.open({
controller: 'MyModalController',
controllerAs: 'vm',
templateUrl : 'templates/CustomModal.html',
size: size,
resolve: {
items: function() {
return {
title: title,
message: message
};
}
}
});
};
return {
open: open
};
}
HTML
<script type="text/ng-template" id="templates/CustomModal.html">
<div class="modal-header">
<h3 class="modal-title">{{vm.content.title}}</h3>
</div>
<div class="modal-body">
{{vm.content.message}}
</div>
<div class="modal-footer">
<button class="ad-button ad-blue" type="button" ng-click="vm.confirm()">
confirm
</button>
<button class="ad-button ad-blue" type="button" ng-click="vm.cancel()">
cancel
</button>
</div>
</script>
<button modal-trigger size="'sm'" title="'Hello World!'" message="'This is a test'">
Click Me
</button>

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();
}

Cordova Ionic refresh side menu after log in and log out

I'm trying to automatically reload my side menu after I log in and log out. I'm doing that by checking my window.localStorage. I've experienced that the side menu won't reload/refresh after I do the action login or logout.
I'm using $state.go('tabs.home') to navigate to another page, but my side menu won't refresh.
Below here is my code:
navCtrl:
app.controller('NavCtrl', function ($scope, $ionicSideMenuDelegate, $rootScope) {
$scope.showMenu = function () {
$ionicSideMenuDelegate.toggleLeft();
};
$scope.showRightMenu = function () {
$ionicSideMenuDelegate.toggleRight();
};
var data = JSON.parse(window.localStorage.getItem("currentUserData"));
if (data != null) {
if (data["id_gebruiker"] == null) {
$rootScope.control = {
showLogin: false,
showLogout: true
};
}
else {
$rootScope.control = {
showLogin: true,
showLogout: false
};
}
}
})
navHtml:
<ion-side-menu-content ng-controller="NavCtrl">
<ion-nav-bar class="bar-positive">
<ion-nav-back-button class="button-icon ion-arrow-left-c">
</ion-nav-back-button>
<ion-nav-buttons side="left">
<button class="button button-icon button-clear ion-navicon" ng-click="showMenu()">
</button>
</ion-nav-buttons>
<ion-nav-buttons side="right">
<button class="button button-icon button-clear ion-ios7-gear" ng-click="showRightMenu()">
</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-nav-view animation="slide-left-right"></ion-nav-view>
</ion-side-menu-content>
loginCtrl:
app.controller('LoginCtrl', function ($scope, $http, $state) {
/*
* This method will be called on click event of button.
* Here we will read the email and password value and call our PHP file.
*/
$scope.check_credentials = function () {
//document.getElementById("message").textContent = "";
$http({ method: 'GET', url: 'http://localhost:34912/api/gebruikers?email=' + $scope.email + '&wachtwoord=' + $scope.wachtwoord }).success(function (data) {
bindUserData(data);
//window.location.reload();
$state.go('tabs.about');
});
function bindUserData(data) {
//alert(JSON.stringify(data));
window.localStorage.setItem("currentUserData", JSON.stringify(data));
}
}
});
app.controller('LogoutCtrl', function ($scope, $http, $state) {
/*
* This method will be called on click event of button.
* Here we will read the email and password value and call our PHP file.
*/
$scope.logout = function () {
var data = JSON.parse(window.localStorage.getItem("currentUserData"));
if (data != null) {
window.localStorage.removeItem("currentUserData");
$state.go('tabs.home');
}
}
});
loginHtml:
<ion-view title="Login">
<ion-content>
<form id="loginForm" ng-app="ionicApp" ng-controller="LoginCtrl">
<div class="list">
<label class="item item-input">
<span class="input-label">Email</span>
<input ng-model="email" type="text" placeholder="Username" />
</label>
<label class="item item-input">
<span class="input-label">Wachtwoord</span>
<input ng-model="wachtwoord" type="password" placeholder="***********" />
</label>
</div>
<div class="padding">
<input type="submit" value="Log on" ng-click="check_credentials()" class="button button-block button-positive" />
</div>
</form>
</ion-content>
I hope you'll understand my problem. I also tried to do a window.location.reload() before $state.go, but that looks buggy. Are there some best practices to fix my problem? Please help me!
Greetings.
Look at the accepted solution at https://stackoverflow.com/a/30524540/1376640
Relevant part of the code is:
$scope.logout = function () {
$ionicLoading.show({
template: 'Logging out....'
});
$localstorage.set('loggin_state', '');
$timeout(function () {
$ionicLoading.hide();
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
$ionicHistory.nextViewOptions({
disableBack: true,
historyRoot: true
});
$state.go('login');
}, 30);
};
Worked for me.
Not a Angular expert but I think that your page will have rebuilt before the $http.get has finished. I got round this by raising an event so where you call bindUserData in the get success change that to $scope.$emit('event', data) then handle the update in a $scope.$on('event'. data). Cut down version of my code below.
controller('AppCtrl', function($scope, $ionicModal, $timeout, MenuData, Data, $ionicActionSheet, UserData, $state, SessionStorage) {
$scope.$on('menuDataChange', function (event, data) {
//refresh menu items data
$scope.items = data;
//clear the state
$state.go($state.current, {}, { reload: true });
});
$scope.items = Data.getItems(SessionStorage.isAuthenticated());
// Form data for the login modal
$scope.loginData = {};
$scope.doLogout = function () {
SessionStorage.clear();
$scope.$emit('menuDataChange', Data.getItems(false)); //Get the menu items for unauthenticated users and raise the change event
};
// Perform the login action when the user submits the login form
$scope.doLogin = function () {
console.log('Doing login', $scope.loginData);
UserData.async($scope.loginData.username, $scope.loginData.password, '12345').then(
// successCallback
function () {
data = UserData.getAll();
var expirationDate = new Date();
expirationDate.setTime(new Date().getTime() + 1200000); //20 minutes
SessionStorage.save({ serverAuthToken: data.d.Items[0].ServerAuthToken, expirationDate: expirationDate });
$scope.$emit('menuDataChange', Data.getItems(true)); //get the menu items for authenticated users and raise the change event
console.log(data);
$state.go('app.home', {}, { reload: true });
},
// errorCallback
function () {
console.log('userdate error');
},
// notifyCallback
function () { }
);
};
})

ng-click function immediately executing function without clicking

I am new to angular and trying to setup a login system. I have some 'buttons' setup to redirect users to an Oauth prompt to users facebook/google account when the button is clicked. My problem is that the function to log users in is executing immediately on page log and not when the button is clicked.
I am pretty sure the root lies in the way JS objects work but I am still learning angularjs and it is a bit confusing.
I believe that putting the functions on the $scope will execute them immediately but I don't see how else I can expose them to the ng-click.
Could someone help me work out how to make the buttons work as expected?
template:
<ion-view title="Account">
<ion-nav-buttons side="right">
<button menu-toggle="right" class="button button-icon icon ion-navicon"></button>
</ion-nav-buttons>
<ion-content class="has-header padding">
<h1 ng-click="google_login()">Log in with Google</h1>
<h1 ng-click="fb_login()">Log in with Facebook</h1>
<h1 ng-click="dev_login()">Dev login</h1>
<div id="logs"></div>
<form class="list">
<label class="item item-input">
<input type="text" placeholder="Username" ng-model="user.username" required>
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="user.password" required>
</label>
<div class="padding">
<button class="button button-block button-stable" ng-click="email_authenticate()">Login</button>
</div>
</form>
</ion-content>
</ion-view>
controller:
.controller('AccountCtrl', function($scope, $state, Authentication) {
$scope.dev_login = Authentication.dev_authenticate(); //executes immediately
$scope.fb_login = Authentication.fb_authenticate(); //executes immediately
$scope.google_login = Authentication.google_authenticate(); //executes immediately
$scope.email_login = Authentication.email_authenticate(); //executes immediately
$scope.logout = Authentication.logout();
});
These are defined in services.js:
.factory('Authentication', function ($http) {
return {
authenticate: function () {
return $http({
url: 'https://api.squawkfinace.com/authenticate',
method: 'post'//,
//data: {facebook_authtoken: key}
});
},
fb_authenticate: function () {
return $.oauth2({
//Oauth details
}, function (token, response) {
localStorage.setItem("LoggedInAccount", JSON.stringify({'platform': 'facebook', 'token': token}));
console.log(token);
$state.transitionTo("app.notifications");
}, function (error, response) {
// do something with error object
});
},
google_authenticate: function () {
return $.oauth2({
//oauth details
}, function (token, response) {
localStorage.setItem("Account", JSON.stringify({'platform': 'google', 'key': token}));
}, function (error, response) {
// do something with error object
$("#logs").append("<p class='error'><b>error: </b>" + JSON.stringify(error) + "</p>");
$("#logs").append("<p class='error'><b>response: </b>" + JSON.stringify(response) + "</p>");
});
},
dev_authenticate: function () {
return null;
},
email_authenticate: function () {
return null;
},
logout: function () {
localStorage.removeItem("Account");
return null;
}
}
});
It's because you're actually executing the functions
$scope.dev_login = Authentication.dev_authenticate();
should be
$scope.dev_login = Authentication.dev_authenticate;
The first scenario executes the function and assigns the result to $scope. You want to assign the reference to the function instead.

Categories