Angularjs Confirmation Modal as Directive with action - angularjs

I want to create angularjs directive mydialog wihc triggers the modal.Once the model is open I will have title and content,okcancel and confirm .Once the user click the confirm the corresponding action i.e. save should trigger .Here the save action is in MainCtrl .How to trigger that.
HTML Directive:
<my-dialog newmodal="alertModel" ></my-dialog>
ConfirmationDailog.html Code :
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ng-click="$hide()">×</button>
<h4 class="modal-title">{{alertModel.Title}}</h4>
</div>
<div class="modal-body">
{{alertModel.Message}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="cancel()">Cancel</button>
<button type="button" class="btn btn-danger" ng-click="executeDialogAction(alertModel.action)">Confirm</button>
</div>
</div>
Below is the JS part :
var app = angular.module('plunker', ['ui.bootstrap']);
app.controller('MainCtrl', ['$scope', '$uibModal',
function ($scope,$uibModal) {
$scope.name = 'World';
var alertModel = {};
alertModel.Title = "My Title";
alertModel.Message = "The Conent";
alertModel.action= "save";
$scope.alertModel = alertModel;
$scope.save= function () {
alert('from outside');
}
}]);
my Dialog Directive that triggers the model
app.directive('myDialog', [
function () {
return {
scope: {
mymodal: '=newmodal',
},
template: "<button class='btn btn-danger' ng-lick='open(mymodal)'>Open Modal</button>",
controller: ModalController
};
}]);
function ModalController($uibModal, $log, $scope) {
$scope.animationsEnabled = true;
$scope.open = function (alertModel) {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'ConfirmationDailog.html',
controller: ModalInstanceCtrl,
scope:$scope,
resolve: {
test: function () {
return alertModel;
}
},
size: 'lg'
});
modalInstance.result.then(function (selectedItem) {
console.log("Confirmed: " + selectedItem);
$scope.selectedItem = selectedItem;
}, function () {
$log.info('modal dismissed at: ' + new Date());
});
};
}
function ModalInstanceCtrl($scope, $uibModalInstance, test) {
console.log('in');
$scope.alertModel = test;
$scope.cancel = function () {
$scope.$dismiss();
}
$scope.executeDialogAction = function (action) {
if (typeof $scope[action] === "function") {
$scope[action]();
}
};
}

Related

Angular bootstrap modal not working

I am working on angular application where I am displaying pop up message using bootstrap modal.
but its not displaying dynamic header text and body text.Pop up is showing but with blank header and body.
my main controller is as below
var requestUserController = function ($scope, $window, $uibModal, DataService) {
$scope.modalOptions = {
headerText: "",
bodyText: ""
}
var onServerError = function (data) {
$scope.modalOptions.headerText = "Error";
$scope.modalOptions.bodyText = data.statusText;
var serverModel = $uibModal.open({
templateUrl: window.serverUrl + 'app/ErrorMessages/PopUpErrorMessage.html',
controller: 'requestUserController',
scope: $scope
});
$scope.cancelForm = function () {
serverModel.close();
};
};
var onClientDataComplete = function (data) {
//window.hideProgress();
$scope.requestUser.clientDrp = data;
$scope.clientSelected = $scope.requestUser.clientDrp[0];
};
//window.showProgress();
DataService.getListofClients()
.then(onClientDataComplete, onServerError);
}
App.controller("requestUserController", ["$scope", "$window", "$uibModal", "DataService", requestUserController]);
and html for modal is
<div class="modal-header" ng-class="{true: 'alert-success', false: 'alert-danger'}[modalOptions.headerText == 'Success']">
<h3>{{modalOptions.headerText}}</h3>
</div>
<div class="modal-body">
<p>{{modalOptions.bodyText}}</p>
</div>
<div class="modal-footer">
<input type="button" class="btn icn-ok" value="Ok"
ng-click="cancelForm()" />
</div>
But pop up is showing blank header and body text
Remove loading of 'requestUserController' from your code and use the following code for open popup window
var serverModel = $uibModal.open({
templateUrl: window.serverUrl + 'app/ErrorMessages/PopUpErrorMessage.html',
scope: $scope
});

Passing modal data in AngularJS using controller as and vm

I have a pair of controllers that looks like this:
(function () {
'use strict';
angular
.module('room')
.controller('RoomGetCtrl', Room)
.controller('TestCtrl', Test)
Room.$inject = [...'$uibModal'...];
Test.$inject = [...'$uibModalInstance'...];
function Room(..., $scope, $uibModal) {
var vm = this;
...
vm.open = function (size) {
vm.modalInstance = $uibModal.open({
templateUrl: 'modal.html',
controller: 'TestCtrl as vm',
});
};
}
function Test(???){
this.modalText = 'Modal Text'
this.modalCancel = function() {
???.dismiss();
}
}
})();
The view looks like this:
<script type="text/ng-template" id="modal.html">
<div class="modal-header">
<h3 class="modal-title">Modal window</h3>
</div>
<div class="modal-body">
<pre>{{ vm.modalText }}</pre>
</div>
<div class="modal-footer">
<button class="btn btn-default" ng-click="vm.modalCancel()">Cancel</button>
</div>
</script>
<button type="button" class="btn btn-default" ng-click="vm.open()">Open me!</button>
...
The above works, except that I'm unable to figure out what goes in the ??? in Test() above. I've tried a variety of things, whenever I click the cancel button, the console logs an error along the lines of "x.dismiss is not a function," where "x" is whatever I've tried use.
Any help?
Nevermind. I instantaneously worked it out myself (I swear, posting the question makes me think better). Anyway, here:
(function () {
'use strict';
angular
.module('room')
.controller('RoomGetCtrl', Room)
.controller('TestCtrl', Test)
Room.$inject = [...,'$uibModal'];
Test.$inject = [$uibModalInstance];
function Room(..., $uibModal) {
/*jshint validthis: true */
var vm = this;
...
vm.open = function () {
vm.modalInstance = $uibModal.open({
templateUrl: 'modal.html',
controller: 'TestCtrl as vm',
});
};
}
function Test($uibModalInstance){
this.modalText = 'Modal Text'
this.modalCancel = function() {
$uibModalInstance.dismiss();
}
}
})();
Really simple. $uibModalInstance.dismiss();. It was right there in the documentation
sigh

unable access controller scope from custom directive

I a trying to access controller scope in my directive but can't access. I created a directive 'dynamicElement' to create new HTML element and its working fine, but in my directive i am not able to access my controller scope.
My Code: Controller
.controller('DashCtrl', function($scope, SurveyQuest, $state, $stateParams, $sce) {
var QuestData = SurveyQuest.all();
if($state.params.qid == ''){
var questionOrder = 1;
}else{
var questionOrder = $state.params.qid;
}
//console.log(QuestData.data[paramQid]);
//console.log(QuestData);
//console.log(QuestData.data.length);
var paramQid;
angular.forEach(QuestData.data, function(value, key) {
if(value.question_order == questionOrder){
paramQid = key;
}
//console.log(value.question_order+' '+key);
});
console.log(paramQid);
console.log(QuestData.data);
$scope.question = $sce.trustAsHtml(QuestData.data[paramQid].question_text);
$scope.description = $sce.trustAsHtml(QuestData.data[paramQid].question_desc);
switch(QuestData.data[paramQid].question_type){
case'radio':
var radioLength = QuestData.data[paramQid].answers.length;
var finalAnswers = '';
for(var i = 0; i < radioLength; i++){
finalAnswers+= '<label><input type="radio" ng-click="clickMe($event)" data-id="'+QuestData.data[paramQid].answers[i].option_next+'" name="'+QuestData.data[paramQid].question_id+'" value="'+QuestData.data[paramQid].answers[i].option_value+'" /> '+QuestData.data[paramQid].answers[i].option_text+'</label>';
}
$scope.htmlString = finalAnswers;
break;
.............
$scope.next = function(qid){
console.log(qid);
$state.go('tab.dash',{'qid':qid});
}
View Code:
<dynamic-element message='htmlString' ng-bind-html="ans"></dynamic-element>
<div class="buttons" style="text-align:center; margin-top:10%;">
<button class="button button-positive">
Prev
</button>
<button class="button button-assertive" >
Stop
</button>
<button class="button button-balanced" ng-click="next({{qid}})">
Next
</button>
</div>
Directive Code:
.directive('dynamicElement', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: {
message: "="
},
replace: true,
link: function(scope, element, attrs) {
var template = $compile(scope.message)(scope);
element.replaceWith(template);
},
controller: ['$scope', function($scope) {
$scope.clickMe = function(item){
$scope.qid = item.currentTarget.getAttribute("data-id"); //NOT WORKING
console.log(item.currentTarget.getAttribute("data-id"));
};
}]
}
}])
Kindly suggest me..Thanks

How to Access HTML Inside of Angular Directive (Transclusion)

I am using angular-ui. I am trying to reduce html coding my making reusable elements with angular directives. I'm definitely missing something. What I want to do is this:
<modal modal-title="Some Title" button-text="Click Me">Modal Content</modal>
And I want that to output the modal and button so instead of adding all that markup over and over for the modal I can just use this custom element. It seems to be working except that I can not for the life of me figure out how to get the content inside of the element. Here's the basics of what I'm doing:
angular.module('app').directive('modal', function () {
return {
templateUrl: 'partials/modal.html',
restrict: 'E',
controller: 'modalController',
controllerAs: 'mCtrl',
transclude: true,
link: function postLink(scope, element, attrs) {
scope.buttonText = attrs.buttonText;
scope.modalTitle = attrs.modalTitle;
}
};
}).controller('modalController', function($scope,$modal,$attrs) {
var _this = this;
this.buttonText = $attrs.buttonText;
this.modalTitle = $attrs.modalTitle;
this.open = function () {
var modalInstance = $modal.open({
templateUrl: 'modal-content.html',
controller: 'ModalInstanceCtrl',
controllerAs: 'miCtrl',
resolve: {
modalTitle: function() { return _this.modalTitle; }
}
});
modalInstance.result.then(function (selectedItem) {
//something
}, function () {
console.info('Modal dismissed at: ' + new Date());
});
};
this.save = function() {
//something
};
}).controller('ModalInstanceCtrl', function ($scope, $modalInstance, modalTitle) {
this.modalValue = 1;
this.modalTitle = modalTitle;
this.ok = function () {
$modalInstance.close(this.modalValue);
};
this.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
Here's the template (partials/modal.html)
<script type="text/ng-template" id="modal-content.html">
<div class="modal-header">
<h3 class="modal-title">{{miCtrl.modalTitle}}</h3>
</div>
<div class="modal-body"> {{ mCtrl.content }} </div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="miCtrl.ok()">OK</button>
<button class="btn btn-warning" ng-click="miCtrl.cancel()">Cancel</button>
</div>
</script>
<button class="btn btn-default" ng-click="mCtrl.open()">{{mCtrl.buttonText}}</button>
How do I get the content of the element into mCtrl.content? The rest of it works as expected, I'm just missing something. Thanks!
Edit: It seems I need to use transclusion, so this is what I want to do:
<div class="modal-body"><ng-transclude></ng-transclude></div>
But I get this kind of error when I open up the modal:
[ngTransclude:orphan] Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <ng-transclude>

Why $scope variable isn't updated?

I have a problem with a scope variable. When i open the form, the content is displayed correctly in the input field. But when I change them and the ok-function fires the changes are not displayed. instead i get the content of form.name. Why isnt the scope updated by the ng-model of the input field?
app.controller('updateFormCtrl', function( $scope, $modalInstance, APIService, form) {
$scope.name = form.name;
$scope.ok = function() {
alert($scope.name)
};
});
View:
<div class="col-sm-10"><input ng-model="name" type="text" class="form-control" placeholder="Categorie"></div>
Edit: Here is the other controller:
$scope.updateForm = function( form ) {
var modalInstance = $modal.open({
templateUrl: 'views/modals/updateForm.html',
controller: 'updateFormCtrl',
resolve: {
form: function() {
return form;
}
}
});
modalInstance.result.then(function() {
$scope.categories = APIService.query({ route:'category' });
});
};
Edit 2:
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="cancel()">Abbrechen</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Speichern</button>
</div><!-- /.modal-footer -->
It's because your $scope.ok isn't defined inside updateFormCtrl. So basically, your ok() cannot read the changes you have made in textbox.
Try moving $scope.ok inside controller.
app.controller('updateFormCtrl', function( $scope, $modalInstance, APIService, form) {
$scope.name = form.name;
$scope.ok = function() {
alert($scope.name)
};
});
I think this is the solution:
https://egghead.io/lessons/angularjs-the-dot

Resources