Pushing item to array after close md-dialog not working - angularjs

Array does not refresh after pushing item through md-dialog, though I can save the item normally.
I tried to test which level I could push an item into the array manually and I could do so until $scope.showAddUsuario(), after that I can't push an item, even manually:
Usuario.html
<div flex-gt-sm="100" flex-gt-md="100" ng-controller="UsuarioCtrl">
<h2 class="md-title inset">Usuario</h2>
<md-card>
<md-list>
...
</md-list>
</md-card>
<md-button class="md-fab" aria-label="Add" ng-click="showAddUsuario($event)">
<md-icon md-svg-icon="content:ic_add_24px" aria-label="Plus"></md-icon>
</md-button>
</div>
md-dialog:
<md-dialog aria-label="Form">
<md-content class="md-padding">
<form name="userForm">
<div layout layout-sm="column">
<md-input-container flex> <label>Nome</label> <input ng-model="item.nome"> </md-input-container>
</div>
<div layout layout-sm="column">
<md-input-container flex> <label>E-mail</label> <input ng-model="item.email"> </md-input-container>
</div>
<div layout layout-sm="column">
<md-input-container flex> <label>Senha</label> <input ng-model="item.senha"> </md-input-container>
</div>
</form>
</md-content>
<div class="md-actions" layout="row">
<span flex></span>
<md-button ng-click="cancel()"> Cancel </md-button>
<md-button ng-click="saveUsuario(item)" class="md-primary"> Save </md-button>
</div>
</md-dialog>
Controller:
app.controller('UsuarioCtrl', function ($scope, $http, $mdDialog, $interval, $timeout) {
$scope.items = [];
$http({
method : 'GET',
url : 'UsuarioServlet'
})
.success(
function(data, status, headers,
config) {
$scope.items = data;
}).error(
function(data, status, headers,
config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$scope.saveUsuario = function(item) {
$scope.items.push({id:100, nome:item.nome, email:item.email, senha:item.senha, status:1});
};
$scope.showAddUsuario = function(ev) {
$mdDialog.show({
controller: 'UsuarioCtrl',
templateUrl : 'CrudUsuario.html',
targetEvent : ev,
locals : {
item : null
}
})
};
});

Only now do I see that you were using $mdDialog and not $modal. So this answer will most likely not apply to your case.
You do however seem to be missing a .finally() part in your code.
From the manual ( https://material.angularjs.org/latest/api/service/$mdDialog )
$mdDialog
.show( alert )
.finally(function() {
alert = undefined;
});
So you could try that.
Otherwise, have you considered using $modal instead?
You don't seem to be handling the return of information from your modal.
(function (){
'use strict';
function myCtrl($modal){
var vm = this;
vm.myArray = [];
...
function openModal(){
var modalInstance = $modal.open({
templateUrl: 'path/to/modal/view.html',
controller: 'MyModalCtrl as vm',
size: 'lg',
resolve: {
data: function(){
return dataThatYouWantToSendFromHereToYourModal;
}
}
});
modalInstance.result.then(function (result){
vm.myArray.push(result);
});
}
...
}
...
})();
The modalIntsance.result.then will trigger when you in your modal-controller (in this case MyModalCtrl) issues a $modalInstance.close(sendThisDataBackToCallingController) call.
So the modal-controller should look along the lines of
...
function MyModalCtrl($modalInstance, data){
...
function init(){
doSomethingWithDataThatYouGotFromTheCallingController(data);
}
...
function save(){
var dataToSendBack = {...};
$modalInstance.close(dataToSendBack);
}
...
}
...
That should get you going in the right direction.

Thanks for the comments! The documentation say to use that:
}).then(function(item) {
$scope.items.push({id:100, nome:item.nome, email:item.email, senha:item.senha, status:1});
});
Works fine!

I solve this problem ,Please replace $mdDialog.show() as
$mdDialog.show({
controller: function (){
this.parent = $scope;
},
templateUrl: 'dialog1.tmpl.html',
scope:$scope.$new(),
targetEvent : ev,
bindToController: true,
clickOutsideToClose:true,
fullscreen: useFullScreen
})

Related

Returned Promise of mdDialog does not work

Seems like my mdDialog popup doesn't work the way it should.
function () {
$mdDialog.show({
templateUrl: 'CameraPopup.html',
clickOutsideToClose: true
}).then(function (answer){ //do something
//with answer
})}
The template looks like this:
<md-dialog >
<form>
<md-dialog-actions layout="column" >
<span flex></span>
<md-button ng-click="answer('camera')">
Open Camera
</md-button>
<md-divider></md-divider>
<md-button ng-click="answer('gallery')">
Open Gallery
</md-button>
</md-dialog-actions>
</form></md-dialog>
I know the problem lies in the promise it returns, but I can't figure why it doesn't work.
Add one controller. Pass that controller into $mdDialog.show. Write answer method into controller.
function () {
$mdDialog.show({
controller: DialogController,
templateUrl: 'CameraPopup.html',
clickOutsideToClose: true
}).then(function (answer){ //do something with answer
});
}
Controller
function DialogController($scope, $mdDialog) {
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
}
});

Method binding is not working in Angular

I am trying to attached a controller scope method in a directive but when i click in directive button that linked method is not called. Please review code. There is side-nav directive in which i have attached method with select parameter. but when button is clicked method is not called.
index.html
<div class="container" layout="row" flex ng-controller="userController as vm" ng-init="vm.loadUsers()">
<md-sidenav md-is-locked-open="true" class="md-whiteframe-1dp">
<side-nav users="vm.users" select="vm.selectUser(user)"></side-nav>
</md-sidenav>
<md-content id="content" flex>
<user-detail selected="vm.selected" share="vm.share()"></user-detail>
</md-content>
</div>
userController.js
app.controller("userController", ['$scope', 'userService', '$mdBottomSheet', function ($scope, userService, $mdBottomSheet) {
var self=this;
self.users = [];
this.name = "manish";
self.loadUsers = function () {
userService
.loadAllUsers()
.then(function (users) {
self.users = users;
self.selected = users[0];
userService.selectedUser = self.selected;
});
}
self.selectUser = function (user) {
self.selected = user;
userService.selectedUser = self.selected;
}
}]);
directives.js
app.directive("sideNav", function () {
return {
restrict :'AE',
templateUrl: './views/sidenav.html',
scope : {
select : '&',
users : '='
}
}
});
./views/sidenav.html
<md-list>
<md-list-item ng-repeat="user in users">
<md-button ng-click="select({user:user)">
<md-icon md-svg-icon="{{user.avatar}}" class="avatar"></md-icon>
{{user.name}}
</md-button>
</md-list-item>
</md-list>
Try doing it like this:
index.html
<side-nav users="vm.users" select="vm.selectUser"></side-nav>
./views/sidenav.html
<md-button ng-click="select()(user)">

Issue in accessing $scope variable in $mdDialog Controller - AngularJs 1.X.X

I'm using $mdDialog and I specified a Controller which is present in another js file.
Parent Js Controller:
$scope.AddDesignationPrompt = function(ev) {
$mdDialog.show({
controller: 'AddDesignationPromptController',
templateUrl: './Employee/Views/AddDesignation.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
fullscreen: true // Only for -xs, -sm breakpoints.
})
.then(function(answer) {
$scope.GetPriliminaryData();
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
Dialog Controller:
app.controller('AddDesignationPromptController', function ($scope, $rootScope, $mdDialog, $window, HTTPService) {
$scope.loadUpData = {
State: [],
Department: [],
Designation: []
};
HTTPService.getPriliminaryRegData().then(function (result) {
if ((result != undefined) && (result != null)) {
$scope.loadUpData = {
State: [],
Department: result.Result.Department,
Designation: []
};
console.log("Inside");
console.log($scope.loadUpData);
}
});
console.log("Outside");
console.log($scope.loadUpData);
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
});
View:
<md-dialog aria-label="Mango (Fruit)">
<form ng-cloak>
<md-toolbar>
<div class="md-toolbar-tools">
<h2>New Department</h2>
<span flex></span>
<md-button class="md-icon-button" ng-click="cancel()">
<md-icon md-svg-src="./Employee/images/Close.svg" aria-label="Close dialog"></md-icon>
</md-button>
</div>
</md-toolbar>
<md-dialog-content>
<div class="md-dialog-content">
<p>Enter the New Department</p>
<div class="controlItem">
<md-select ng-model="select.designation" ng-change="onDesignationChange(select.designation)" tabindex="9">
<md-option ng-repeat="key in loadUpData.Designation" value="{{key.DesignationId}}">{{key.Name}}</md-option>
</md-select>
</div>
</div>
</md-dialog-content>
<md-dialog-actions layout="row">
<span flex></span>
<md-button ng-click="answer('not useful')">
Not Useful
</md-button>
<md-button ng-click="answer('useful')">
Useful
</md-button>
</md-dialog-actions>
</form>
</md-dialog>
Its coming in controller level, but its not loading in md-select. Kindly assist me how to load the collection in the View.
You are looping over loadUpData.Designation which is always set to empty array [], so nothing will be ever displayed. The only data that is populated in your HTTPService promise resolve is loadUpData.Department, but you never print it in your HTML.
if you have Designation in result, than populate it, something like:
HTTPService.getPriliminaryRegData().then(function (result) {
if (result && result.Result) {
$scope.loadUpData = {
State: [],
Department: result.Result.Department,
Designation: result.Result.Designation
};
console.log("Inside");
console.log($scope.loadUpData);
}
});

ng-click does not fire the second time with mdDialog

I'm new to angular JS. I'm trying to create a simple mdDialog which contains a form for signing up.
I works the first time but the ng-click does not respond the second time. I don't get any errors in console.
It works on page reload again.
HTML
<div ng-controller="UsersController as uc">
<a ng-click="uc.signUp()">Click here to sign up for the newsletter!</a>
</div>
Controller
function subscribe() {
var successHandler = function () {
$mdDialog.show(
$mdDialog.alert()
.title('Subscription processed')
.textContent('Thank you for signing up')
.ok('Ok')
);
};
if (self.email) {
UsersService.subscribe(self.email, self.firstName, self.lastName).then(successHandler, errorHandler);
self.email = '';
self.firstName = '';
self.lastName = '';
$timeout(function () {
self.showSubscribe = false;
});
}
}
function signUp() {
$mdDialog.show({
clickOutsideToClose: true,
scope: $scope,
templateUrl: '/view/templates/subscribe.html',
controller: function DialogController($scope, $mdDialog) {
$scope.cancel = $mdDialog.cancel;
}
});
}
Template:
<div class="newsletter" layout="row" layout-align="center start" flex>
<form class="form" name="newsletterForm" ng-submit="uc.subscribe();">
<div>... </div>
</form>
<div class="toolbar" flex-auto="10">
<md-button class="md-icon-button" ng-click="cancel()">
<md-icon aria-label="Close">clear</md-icon>
</md-button>
</div>

Cannot get input value from md-input

I have this md-dialog which has an input. I'm passing the model of the input when I click the top up button but on my controller, it is undefined.
<md-dialog aria-label="Top Up User" ng-cloak>
<md-dialog-content>
<div class="md-dialog-content">
<form>
<md-input-container class="md-block">
<label>Amount</label>
<input required type="number" name="amount" ng-model="topup.amount" min="1"
ng-pattern="/^1234$/" />
</md-input-container>
<md-dialog-actions layout="row" ng-show="!vm.loading">
<md-button ng-click="vm.closeDialog()">
Cancel
</md-button>
<md-button ng-click="vm.topUp(topup.amount)" style="margin-right:20px;">
Top Up
</md-button>
</md-dialog-actions>
<div layout="row" layout-align="space-around">
<md-progress-circular md-mode="indeterminate" ng-show="vm.loading"></md-progress-circular>
</div>
</form>
</div>
</md-dialog-content>
</md-dialog>
Controller:
(function(){
angular
.module('app')
.controller('MainController', [
'navService', '$mdSidenav', '$mdDialog', '$log', '$q', '$state', '$mdToast', 'Pubnub', 'mongolabService', '$scope',
MainController
]);
function MainController(navService, $mdSidenav, $mdDialog, $log, $q, $state, $mdToast, Pubnub, mongolabService, $scope) {
var vm = this;
function showActions($event) {
var self = this;
$mdDialog.show({
controller: [ '$mdDialog', TopUpController],
controllerAs: 'vm',
templateUrl: 'app/views/partials/topup.html',
targetEvent: $event,
bindToController : true,
clickOutsideToClose:true
});
function TopUpController () {
var vm = this;
vm.topUp = topUp;
vm.loading = false;
vm.closeDialog = closeDialog;
function closeDialog() {
$mdDialog.hide();
}
function querySearch (query) {
return query ? $scope.users.filter( createFilterFor(query) ) : $scope.users;
}
function topUp(amount) {
var topUpCallback = {
error: function(response){
vm.loading = false;
showSimpleToast("Error occurred");
console.log(response);
}, success: function(response){
showSimpleToast("Top up success");
}
}
//Amount is undefined
showSimpleToast("amount: " + amount);
}
}
}
function showSimpleToast(title) {
$mdToast.show(
$mdToast.simple()
.content(title)
.hideDelay(2000)
.position('bottom right')
);
}
}
})();
Its strange. change
showSimpleToast("amount: " + amount);
to
showSimpleToast("amount: " + vm.amount);
and let see what happens
Can you change the way you're using topup property like this (just for 1 style coding vm/$scope):
In input
<input required type="number" name="amount" ng-model="vm.topup.amount" min="1" ...
In button:
<md-button ng-click="vm.topUp(topup.amount)" style="margin-right:20px;">
And init topup object in your controller:
vm.topup = {amount: ''};
I think the problem is you didn't init your topup object before use its amount property
I noticed that the amount is just getting undefined when I type on the input. I added allowInvalid to the <input> and it worked.
ng-model-options="{allowInvalid: true}"

Resources