Angular Bootstrap modal with embedded directive -- can't get value out? - angularjs

I have a pretty simple custom directive which presents a form to enter a numeric value. This directive is embedded inside a modal dialog box that is triggered when required. While I can pass data into the dialog through the modal, I am having trouble getting data entered in the input element within the directive back out when the user clicks "OK". I imagine it has something to do with the scope of the directive, since I am using isolate scope, but I marked the name with '=' in the scope section, so I'm not sure what is going wrong.
Here is the plunker that demonstates the issue. Plunker example
var app = angular.module('plunker', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
app.controller('MainCtrl', function($scope, $uibModal, $log, $document) {
var self = this;
var $ctrl = self;
$ctrl.modalresult = "no result";
$ctrl.name = 'World';
$ctrl.myvalue = "-99";
$ctrl.openGetConstantDialog = function(varname, parentSelector, size) {
var parentElem = parentSelector ?
angular.element($document[0].querySelector(parentSelector)) : undefined;
$ctrl.modalInstance = $uibModal.open({
animation: $ctrl.animationsEnabled,
template: `<get-numeric-dialog title="Define a New Constant"
prompt="Enter a value for constant"
varname="${varname}" placeholder="Enter a numeric value">
</get-numeric-dialog>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="$ctrl.ok(myvalue)">OK</button>
<button class="btn btn-warning" type="button" ng-click="$ctrl.cancel()">Cancel</button>
</div>`,
controller: 'ModalInstanceCtrl',
controllerAs: '$ctrl',
size: 'sm',
appendTo: parentElem
});
$ctrl.modalInstance.result.then(function(value) {
$ctrl.modalresult = $ctrl.myvalue;
console.log("modal instance returned value: ", $ctrl.myvalue);
},
function() {
$ctrl.modalresult = "no value returned"
}
);
}
});
app.controller('ModalInstanceCtrl', function($uibModalInstance, $scope) {
var $ctrl = this;
$ctrl.value = undefined;
$ctrl.ok = function() {
$uibModalInstance.close($ctrl.newValue);
};
$ctrl.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
});
app.directive('getNumericDialog', [function() {
return {
templateUrl: 'get_numeric_dialog.html',
restrict: 'E',
scope: {
title: '#',
prompt: '#',
varname: '#',
placeholder: '#',
myvalue: '='
}
};
}]);
Here's the directive template:
<div class="modal-header">
<h5 class="modal-title" id="modal-title">{{title}}</h5>
</div>
<div class="modal-body" id="modal-body">
<p>{{prompt}} '<span class="bold">{{varname}}</span>'</p>
<input type='text' placeholder='{{placeholder}}' ng-model="value"><br>
</div>

I managed to get this working after a couple of days, not quite structured as above, because an embedded directive ultimately wasn't worth the additional complexity, but in case anybody else is having trouble, solution below.
var app = angular.module('plunker', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
app.controller('MainCtrl', function($scope, $uibModal, $log, $document) {
var self = this;
var $ctrl = self;
$scope.modalresult = "no result";
$scope.openModal = function() {
var getConstantTemplate = function(title, prompt, buttonCaption, varName) {
let template = `<div class="modal-header">
<h5 class="modal-title" id="modal-title">${title}</h5>
</div>
<div class="modal-body" id="modal-body">
<p>Value for constant '<span class="bold">${varName}</span>':</p>
<input type='text' varname="weeks" placeholder='Enter a number' ng-model="$ctrl.newValue">
<br>
</div>
<div class = "modal-footer" id="modal-footer">
<button class="btn btn-primary" type="button" ng-click="$ctrl.ok()">${buttonCaption}</button>
<button class="btn btn-warning" type="button" ng-click="$ctrl.cancel()">Cancel</button>
</div>`
return template;
}
var modalInstance = $uibModal.open({
animation: true,
template: getConstantTemplate("New Constant", "a", "Save", "months"),
controller: 'ModalInstanceCtrl',
controllerAs: '$ctrl',
size: 'sm'
});
modalInstance.result.then(function(result) {
console.log('modalInstance got result ' + result);
$scope.modalresult = result;
});
};
});
app.controller('ModalInstanceCtrl', function($scope, $uibModalInstance) {
var $ctrl = this;
$ctrl.prompt = "Enter a value for constant ";
$ctrl.varname = "weeks";
$ctrl.placeholder = "Enter a number";
$ctrl.ok = function() {
console.log("OK has been called with newValue " + $ctrl.newValue);
$uibModalInstance.close($ctrl.newValue);
};
$ctrl.cancel = function() {
console.log("Cancel has been called");
$uibModalInstance.close("model closed cancelled");
};
})
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker </title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<script src="app2.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-app="plunker">
<div ng-controller="MainCtrl as ctrl">
<button ng-click="openModal()">Open the modal please</button>
<br>
<br>
<p>modalresult = {{modalresult}} </p>
</div>
</body>
</html>

Related

angularjs $uimodal needs to be updated

i have a peculiar scenario, where my data gets updated even after a modal window is open. i am supposed to refresh the data on the modal pop-up by adding a new item on the modal popup.
Here is the plunker, i tried to pass $rootScope, but from documentation, realized that default scope passed is $rootScope.
My plunker link is
https://plnkr.co/edit/hnMGHfsxPfq8BRCtVxqJ
I'm using angular ui bootstrap and using $uibModal
Please suggest a solution i can try.
In my plunker code, even if the $item is updated, my modal isnt being refreshed.
<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ModalDemoCtrl as $ctrl" class="modal-demo">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title" id="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body" id="modal-body">
<ul>
<li ng-repeat="item in $ctrl.items">
{{ item }}
</li>
</ul>
Selected: <b>{{ $ctrl.selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="$ctrl.ok()">OK</button>
<button class="btn btn-warning" type="button" ng-click="$ctrl.cancel()">Cancel</button>
</div>
</script>
<script type="text/ng-template" id="stackedModal.html">
<div class="modal-header">
<h3 class="modal-title" id="modal-title-{{name}}">The {{name}} modal!</h3>
</div>
<div class="modal-body" id="modal-body-{{name}}">
Having multiple modals open at once is probably bad UX but it's technically possible.
</div>
</script>
<button type="button" class="btn btn-default" ng-click="$ctrl.open()">Open me!</button>
<button type="button" class="btn btn-default" ng-click="$ctrl.additems()">Add Item</button>
{{ $ctrl.items}}
<div class="modal-parent">
</div>
</div>
</body>
</html>
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($uibModal, $log, $document) {
var $ctrl = this;
$ctrl.items = ['item1', 'item2', 'item3'];
$ctrl.animationsEnabled = true;
$ctrl.additems = function (){
$ctrl.items.push("item"+($ctrl.items.length+1));
};
$ctrl.open = function (size, parentSelector) {
var parentElem = parentSelector ?
angular.element($document[0].querySelector('.modal-demo ' + parentSelector)) : undefined;
var modalInstance = $uibModal.open({
animation: $ctrl.animationsEnabled,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
controllerAs: '$ctrl',
size: size,
appendTo: parentElem,
resolve: {
items: function () {
return $ctrl.items;
}
}
});
setTimeout(function () {
$ctrl.items.push("item"+($ctrl.items.length+1));
}, 1000);
modalInstance.result.then(function (selectedItem) {
$ctrl.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$ctrl.toggleAnimation = function () {
$ctrl.animationsEnabled = !$ctrl.animationsEnabled;
};
});
// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($uibModalInstance, items) {
var $ctrl = this;
$ctrl.items = items;
$ctrl.selected = {
item: $ctrl.items[0]
};
$ctrl.ok = function () {
$uibModalInstance.close($ctrl.selected.item);
};
$ctrl.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});
My issue specifically is here, the Modal is rendered already with items passed.
ctrl.items is updated after 1 second, but the modal window where items is passed is not updated. Is there a way i can send an update of $ctrl.items to modal window
setTimeout(function () {
$ctrl.items.push("item"+($ctrl.items.length+1));
}, 1000);
Your question was not very clear. From your plunkr I see that the modal data gets updated when the original data is modified. So, assuming that's your problem: Javascripts objects are copied by reference. So to avoid that you need to create a new copy of the object. Like so:
items: function () {
return angular.copy($ctrl.items);
}
Updated plunkr: https://plnkr.co/edit/pHDr0B0jWRBGeNSPu0t7?p=preview

How do I display the inner html of directive inside a dialog?

What do I want to do?
I want to have a directive with some html inside. The directive renders a button and when the button is clicked I open a modal dialog. I want to display the html declared inside the directive in the dialog. Different spots where I use the directive might have different html messages in the modal dialog.
Here is the code that I've got.
app.js:
var app = angular.module('plunker', ['ngResource', 'ui.bootstrap', 'ui.bootstrap.modal']);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
})
.controller('dialogController', ['$scope', '$modalInstance', 'params', function ($scope, $modalInstance, params) {
$scope.info = params.info;
$scope.close = function () {
$modalInstance.dismiss('cancel');
};
}])
.directive('someDirective', ['$modal', '$timeout', function ($modal, $timeout) {
return {
scope: {
title: '#title'
},
restrict: 'AE',
replace: true,
templateUrl: 'someDirective.html',
transclude: true,
link: function ($scope, $element, attr, controller, transclude) {
//transclude(function(clone, scope) {
// debugger;
// });
$scope.info = "test"; // I would like to set this to the value within the inner html of the directive.
$scope.openDialog = function () {
var modalInstance = $modal.open({
templateUrl: 'dialog.html',
controller: 'dialogController',
backdrop: 'static',
windowClass: 'ie-app-modal-window-narrow',
resolve: {
params: function () {
return {
info: 'SomeHtml' //<-- here I want to it to the html from inside someDirective
};
}
}
});
modalInstance.result.then(function () {
},
function () { });
};
}
};
}])
;
dialog.html:
<!DOCTYPE html>
<html>
<head>
<title>Add attachment</title>
<meta charset="utf-8"/>
</head>
<body>
<div class="modal-header">
<button type="button" class="close"><span aria-hidden="true" ng-click="close()">×</span></button>
<strong>Add Attachment</strong>
</div>
<div class="modal-body">
<!-- Text input-->
<div class="alert alert-info" role="alert">
{{info}}
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<div style="float: left">
<button class="btn btn-default" ng-click="close()" ng-disabled="isDisabled">Close</button>
</div>
</div>
</div>
</body>
</html>
index.html:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script data-require="jquery#2.2.4" data-semver="2.2.4" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script data-require="bootstrap#3.3.7" data-semver="3.3.7" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script data-require="angular-ui#0.4.0" data-semver="0.4.0" src="http://rawgithub.com/angular-ui/angular-ui/master/build/angular-ui.js"></script>
<script data-require="angular-ui-bootstrap#1.3.3" data-semver="0.12.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.min.js"></script>
<script data-require="angular-resource#1.2.28" data-semver="1.2.28" src="https://code.angularjs.org/1.2.28/angular-resource.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<some-directive title="Hello">
<b>Testing</b>
</some-directive>
</body>
</html>
someDirective.html:
<div class="panel panel-default" >
<div class="panel-heading">
{{title}}
</div>
<div class="panel-body" ng-style="loadingStyle">
<button class="btn btn-sm btn-default" ng-click="openDialog();" type="button">Open</button>
</div>
</div>
I found this: How to get inner html of custom directive? but I don't know exactly how it would work in my case. I am not using the compile method.
Plnker
Thanks
To Pass value from someDirective to dialog.
First inject $rootScope into someDirective like so:
directive('someDirective', ['$modal', '$timeout', '$rootScope', function ($modal, $timeout, $rootScope) {
Now we create a new scope and add a value to it (in this case, $scope.info), and pass it into the modalScope. angular will then pass this along to the modal's controller as the $scope variable.
$scope.info = "test";
$scope.openDialog = function () {
var modalScope = $rootScope.$new();
modalScope.info = $scope.info;
var modalInstance = $modal.open({
scope: modalScope,
templateUrl: 'dialog.html',
controller: 'dialogController',
backdrop: 'static',
windowClass: 'ie-app-modal-window-narrow',
});
modalInstance.result.then(function () {
},
function (result) {
});
};
So inside the modal's controller we have access to variable we just passed in!
.controller('dialogController', ['$scope', '$modalInstance', function ($scope, $modalInstance) {
console.log($scope.info); //prints "test"
$scope.close = function () {
$modalInstance.dismiss('cancel');
};
}])
Now the opposite. To pass from modal back to someDirective:
There's several ways but in my opinion the best way is to use the promises. modalInstance.result returns a promise. This promise is resolved if the modal is closes and rejected if the modal is dismissed. Whether resolved or rejected, a value/object can be passed along as a parameter.
Example, opening the dialog as before:
$scope.info = "test";
$scope.openDialog = function () {
var modalScope = $rootScope.$new();
modalScope.info = $scope.info;
var modalInstance = $modal.open({
scope: modalScope,
templateUrl: 'dialog.html',
controller: 'dialogController',
backdrop: 'static',
windowClass: 'ie-app-modal-window-narrow',
});
modalInstance.result.then(function (returnStuff) {
//This is called when the modal is closed.
//returnStuff is whatever you want to return from the dialog when it's closed
},
function (returnStuff) {
//This is called when the modal is dismissed.
//returnStuff is whatever you want to return from the dialog when it's dismissed
});
};
And to actually close/cancel the dialog:(from inside the dialog)
//pass any value you want back
$modalInstance.close({foo:"Ayyylmao", bar:42});
$modalInstance.dismiss('dismissed');
If I understood it correctly, this is what you want, http://plnkr.co/edit/tOe8tZ5VWfOCkocQaEKo?p=preview
$scope.info = $element.get(0).innerHTML.trim();
Based on this posting, I managed to find something that works for the specific angularjs versions that I am using. I made another plnkr.
The relevant changes are:
dialog.html: I used <div ng-bind-html="info"></div>
<!DOCTYPE html>
<html>
<head>
<title>Add attachment</title>
<meta charset="utf-8"/>
</head>
<body>
<div class="modal-header">
<button type="button" class="close"><span aria-hidden="true" ng-click="close()">×</span></button>
<strong>Add Attachment</strong>
</div>
<div class="modal-body">
<!-- Text input-->
<div class="alert alert-info" role="alert">
<div ng-bind-html="info"></div>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<div style="float: left">
<button class="btn btn-default" ng-click="close()" ng-disabled="isDisabled">Close</button>
</div>
</div>
</div>
</body>
</html>
app.js - I added the controller property in the someDirective directive and the code grabs the html and sets the info property.
var app = angular.module('plunker', ['ngResource', 'ui.bootstrap', 'ui.bootstrap.modal']);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
})
.controller('dialogController', ['$scope', '$modalInstance', 'params', function($scope, $modalInstance, params) {
$scope.info = params.info;
$scope.close = function() {
$modalInstance.dismiss('cancel');
};
}])
.directive('someDirective', ['$modal', '$timeout', '$sce', function($modal, $timeout, $sce) {
return {
scope: {
title: '#title',
html: '#'
},
restrict: 'AE',
replace: true,
templateUrl: 'someDirective.html',
transclude: true,
controller: function($scope, $element, $attrs, $transclude) {
$transclude(function(clone,scope){
$scope.info = angular.element('<div>').append(clone).html().trim();
});
},
link: {
pre: function (scope, iElement, iAttrs, controller) {
//debugger;
},
post: function($scope, $element, attr, controller) {
//transclude(function(clone, scope) {
// debugger;
// });
//debugger;
//$scope.info = "test"; // I would like to set this to the value within the inner html of the directive.
//debugger;
$scope.openDialog = function() {
var modalInstance = $modal.open({
templateUrl: 'dialog.html',
controller: 'dialogController',
backdrop: 'static',
windowClass: 'ie-app-modal-window-narrow',
resolve: {
params: function() {
return {
info: $sce.trustAsHtml($scope.info) //<-- here I want to set it to the html from inside someDirective
};
}
}
});
modalInstance.result.then(function() {},
function() {});
};
}
}
};
}])
;

UI Grid row data to Textarea

Following is my angular script :
angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.selection'])
.controller('MainCtrl', ['$scope', function ($scope) {
var vm = this;
vm.gridOptions = { multiSelect:false};
vm.reset = reset;
function reset() {
vm.gridOptions.mydata = [];
vm.gridOptions.columnDefs = [];
}
}])
.directive("fileread", [function () {
return {
scope: {
opts: '='
},
link: function ($scope, $elm, $attrs) {
$elm.on('change', function (changeEvent) {
var reader = new FileReader();
reader.onload = function (evt) {
$scope.$apply(function () {
var mydata = evt.target.result;
var workbook = XLSX.read(mydata, {type: 'binary'});
var headerNames = XLSX.utils.sheet_to_json( workbook.Sheets[workbook.SheetNames[0]], { header: 1 })[0];
var mydata = XLSX.utils.sheet_to_json( workbook.Sheets[workbook.SheetNames[0]]);
$scope.opts.columnDefs = [];
headerNames.forEach(function (h) {
$scope.opts.columnDefs.push({ field: h });
});
$scope.opts.data = mydata;
$elm.val(null);
});
}
reader.readAsBinaryString(changeEvent.target.files[0]);
});
}
}
}]);
app.controller('MainCtrl', ['$scope', '$http', '$interval', 'uiGridConstants', function ($scope, $http, $interval, uiGridConstants) {
$scope.mySelections = [];
$scope.gridOptions.multiSelect = false;
$scope.gridOptions.modifierKeysToMultiSelect = false;
$scope.gridOptions.noUnselect = true;
$scope.gridOptions.onRegisterApi = function( gridApi ) {
$scope.gridApi = gridApi;
$scope.gridApi.selection.on.rowSelectionChanged($scope, function(rows) {
$scope.mySelections = $scope.gridOptions.data[0];
var v = {mySelections};
var z = document.getElementById("t");
z.innerHTML.append = v;
});
}
$scope.toggleRowSelection = function() {
$scope.gridApi.selection.clearSelectedRows();
$scope.gridOptions.enableRowSelection = !$scope.gridOptions.enableRowSelection;
$scope.gridApi.core.notifyDataChange( uiGridConstants.dataChange.OPTIONS);
};
$http.get('/mydata/500_complex.json')
.success(function(mydata) {
$scope.gridOptions.data = mydata;
$scope.gridOptions.multiSelect.data = false;
// $interval whilst we wait for the grid to digest the data we just gave it
$interval( function() {
$scope.gridApi.selection.selectRow($scope.gridOptions.data[0]);}, 0, 1);
$scope.mySelections = $scope.gridOptions.data[0];
var v = {mySelections};
var z = document.getElementById("t");
z.innerHTML.append = v;
});
}]);
Following is my HTML code :
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-touch.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
<script src="https://cdn.rawgit.com/SheetJS/js-xlsx/v0.8.0/dist/xlsx.full.min.js"></script>
<script src="https://cdn.rawgit.com/SheetJS/js-xlsx/v0.8.0/dist/ods.js"></script>
<script src="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.22/ui-grid.min.js"></script>
<link rel="stylesheet" href="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.22/ui-grid.min.css" />
<link rel="stylesheet" href="main.css" type="text/css" />
</head>
<body>
<div ng-controller="MainCtrl as vm">
<button type="button" class="btn btn-success" ng-click="vm.reset()">Reset Grid</button>
<br />
<br />
<div id="grid1" ui-grid="vm.gridOptions" ui-grid-selection class="grid">
<div class="grid-msg-overlay" ng-show="!vm.gridOptions.data.length">
<div class="msg">
<div class="center">
<span class="muted">Select Spreadsheet File</span>
<br />
<input type="file" accept=".xls,.xlsx,.ods" fileread="" opts="vm.gridOptions" multiple="false" />
</div>
</div>
</div>
</div>
</div>
<script src="app.js"></script>
<br />
**<textarea id = "t" style="width:100%"></textarea>**
<br/>
<button id="copy" name="copy" type="button" class="btn btn-success" ng-click="vm.copy()">Copy</button>
</body>
</html>
I want to show selected row in textarea.
Done selecting row at a time,but not able to show data in textarea?
Any suggestion appreciated as I am beginner.

Angular UI bootstrap modal is not working

I am new to angular and bootstrap. This is my Plunk.
This is my code of DemoController:
angular.module('app', ['ui.bootstrap'])
.controller('demoController', function($modal) {
this.message = 'It works!';
key = 1000;
this.modalInstance = this.modal = function(){
$modal.open({
controllerAs: 'modalController as modal',
templateUrl: 'modal.html',
resolve: {
key: function() {
return key;
}
}
});
};
this.modalInstance.result.then(function (optionSelected){
if(optionSelected == 'yes')
{
}
});
});
ModalController:
angular.module('app')
.controller('modalController', function($scope, $modalInstance, key) {
$scope.featureName = key;
$scope.yes = function () {
$modalInstance.close('yes');
};
$scope.discard = function () {
$modalInstance.close('discard');
};
$scope.goback = function () {
$modalInstance.close('goback');
};
});
Modal.html:
<script type="text/ng-template" id="modal.html">
<div class="modal-content">
<div class="modal-body">
<p>Do you want to save the changes to {{featureName}} </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="yes()">Yes</button>
<button type="button" class="btn btn-default" ng-click="discard()">Discrad</button>
<button type="button" class="btn btn-default" ng-click="goback()">Go Back</button>
</div>
</div>
</script>
Index.html:
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap-css#3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<script data-require="angular.js#1.2.16" data-semver="1.2.16" src="https://code.angularjs.org/1.2.16/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.11.0/ui-bootstrap-tpls.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="demoController as demo">
<h1>{{ demo.message }}</h1>
<button class="btn btn-primary" ng-click="demo.modal()">Open modal</button>
</body>
</html>
I want to pass data from demo controller to modal controller. I want to have separate html and controller for the modal dialog. Somehow this is not working.
Here's a working plunker based on your own plunk: http://plnkr.co/edit/VDDyDuBoZ30tAk2kQKoc?p=preview
List of changed things:
In index.html, I added Ctrl.js to the list of loaded scripts.
In modal.html, removed the script tags surrounding the html. When loading the modal html from an external file, the script tags aren't necessary.
Finally in script.js made a few changes, ending up with the following:
angular.module('app', ['ui.bootstrap'])
.controller('demoController', function($modal) {
this.message = 'It works!';
var key = 1000;
this.modal = function() {
var modalInstance = $modal.open({
controller: 'modalController',
templateUrl: 'modal.html',
resolve: {
key: function() {
return key;
}
}
});
modalInstance.result.then(function(optionSelected) {
if (optionSelected === 'yes') {
console.log("Yes selected!")
}
})
}
});
Basically, this.modal is the function that's executed when clicking on the Open modal button. In the function, we initialize a variable modalInstance, which is the $modal.open function call. We also handle the modal result inside the this.modal function, not outside of it.
You have a lot of mistakes there. Here is your example:
plnkr.co/edit/47WJrWHW7ueYXBpiYJbA?p=preview

AngularJS textbox returns undefined value

When I press my button check in bootstrap modal, I want to print the value of my textbox in my console. But my textbox returns a undefined. It seems that all of the code are working perfect.
<!doctype html>
<html ng-app="app" ng-controller="ModalDemoCtrl">
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>
<script src="example1.js"></script>
</head>
<body>
<div ><button class="btn btn-default" ng-click="open('lg')" >Large modal</button>
<script type="text/ng-template" id="myModalContent">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<input type="text" ng-model="new1" /><button ng-click="check()" >check</button>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
</div>
</body>
</html>
This is my javascript
var app = angular.module('app', ['ui.bootstrap']);
//var ModalDemoCtrl = function ($scope, $modal, $log) {
app.controller('ModalDemoCtrl',['$scope', '$modal','$log','$rootScope',
function controller($scope, $modal, $log, $rootScope)
{
$scope.open = function (size) {
$scope.val = "";
var modalInstance = $modal.open({
templateUrl: 'myModalContent',
controller: ModalInstanceCtrl,
size: size,
backdrop: 'static',
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
}]);
var ModalInstanceCtrl = function ($scope,$rootScope, $modalInstance) {
$scope.check = function()
{
console.log($scope.new1);
};
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
In order to access the $scope variable you need to use $parent as it is creating a child scope in the modal
HTML Code (This is changed):
<input type="text" ng-model="$parent.new" /><button ng-click="check()" >check</button>
Working Fiddle
declare new property on object initialize instead of scope:
var ModalInstanceCtrl = function ($scope,$rootScope, $modalInstance) {
$scope.model= {};
$scope.check = function()
{
alert($scope.model.new);
};
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
http://plnkr.co/edit/A6I158T9I5kGyChgIDK2?p=preview
You can pass the ng-model as parameter in "Check" function
<input type="text" ng-model="new1" /><button ng-click="check(new1)" >check</button>
$scope.check = function(new1)
{
console.log("value..."+new1);
};

Resources