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

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

Related

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>

$mdDialog not working

$mdDialog not working with custom template.
here's the code:
HTML:
<md-button class="md-icon-button" ng-click="commentPrompt($event)">
<p>button
</p>
</md-button>
JS:
var app = angular.module('BetaApp', ['ngMaterial', 'firebase']);
app.controller('SideNavController', function($scope, $mdDialog) {
$scope.commentPrompt = showDialog;
function showDialog($event){
var parentEl = angular.element(document.body);
$mdDialog.show({
parent: parentEl,
targetEvent: $event,
templateUrl: 'comment.html',
controller: DialogController
});
};
function DialogController($scope, $mdDialog) {
$scope.closeDialog = function() {
$mdDialog.hide();
}
}
});
COMMENT.HTML:
<md-dialog>
<span>test
</span>
<md-button ng-click="closeDialog()" class="md-primary">
<p>close</p>
</md-button>
</md-dialog>
change this
md-button class="md-icon-button" ng-click="commentPrompt($event)">
to
md-button class="md-icon-button" ng-click="showDialog($event)">

Pushing item to array after close md-dialog not working

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

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}"

Add dropdown menu inside sidebar with material design?

I would like when click on polls , open dropdown menu which include sub categories of pulls.
How i should change my code in order to add this functionality with material design.
In state provider:
$stateProvider
.state('admin', {
/*abstract: true,*/
url: '/admin',
templateUrl: 'app/admin/admin.html',
controller: 'AdminCtrl',
onEnter: function($rootScope) {
$rootScope.title = $rootScope.titleRoot + ' | Admin';
}
});
});
and in .html
<md-sidenav class="md-sidenav-left md-whiteframe-z2" md-component-id="left" md-is-locked-open="$mdMedia('gt-md')">
<md-toolbar class="md-theme-indigo">
<h1 class="md-toolbar-tools">Admin</h1>
</md-toolbar>
<md-content class="" ng-controller="LeftCtrl">
<md-button ng-click="close()" class="md-primary" hide-gt-md>
Close Sidenav Left
</md-button>
<!--<p hide-md show-gt-md>-->
<!--</p>-->
<ul class="sidenav-menu">
<li class="" ng-repeat="section in sections">
<md-button ui-sref="{{section.link}}">
<i class="fa fa-fw {{section.icon}}"></i> {{section.title}}
</md-button>
</li>
</ul>
</md-content>
</md-sidenav>
Inside Controller:
.controller('AdminCtrl', function($scope, $mdSidenav, $timeout, $log) {
$scope.sections = [
{
title: 'User Management',
icon: 'fa-user',
link: 'usermanagement'
},{
title: 'Polls',
icon: 'fa-files-o',
link: 'polls'
}
];
$scope.toggleLeft = function () {
$mdSidenav('left').toggle()
.then(function () {
//$log.debug("toggle left is done");
});
};
})
.controller('LeftCtrl', function($scope, $timeout, $mdSidenav, $log) {
$scope.close = function() {
$mdSidenav('left').close()
.then(function(){
//$log.debug("close LEFT is done");
});
};
});
Since you are using Angular-Material, I suggest you use it's Menu directive: https://material.angularjs.org/latest/#/demo/material.components.menu

Resources