How to set default value of custom radio button in a modal - angularjs

Background:
So I am working with a modal box for searching through a list of task entries within a database using a form to narrow results. In this modal box, there is a custom radio button that's used for selecting whether or not the task is in progress (simple "Yes" or "No" option). The goal is to set the "No" option as the default value whenever the modal is called. Currently, I am using data-ng-init; however, this only works the first time the modal is opened. If the user closes the modal and reopens it, the default value is no longer set. Below is a sample of what this custom button looks like:
<div class="col-sm-6">
<div style="margin-bottom:10px">
<button type="button" data-ng-init="tr.taskInProgress('No')"
title="Task In Progress: No" data-ng-click="tr.taskInProgress('No')"
style="border:0;background:transparent">
<img src="../images/selected.png" data-ng-switch-when="No" />
<img src="../images/Deselect.png" data-ng-switch-when="Yes" />
<img data-ng-switch-when="" src="/nc/images/Deselect.png" /></button>
<text>No
</div>
(another similar button, but for 'yes')
</div>
In the accompanying .js file, the following is used to help populate this modal:
/*--------- Get Tasks ---------*/
tr.closeGetTaskModal = closeGetTasModal;
tr.displayGetTaskMessage = true;
tr.selectedStatusType = getStatusType;
tr.trackingId = '';
tr.performGetTask = performGetTask;
tr.isTaskInProgess = isTaskInProgress;
And, in the same .js file, the following function is used to modify the radio:
function isTaskInProgress(newValue) {
tr.isTaskInProgress = newValue;
}
I have been looking through others iterations on how they handle such cases, but I have been unlucky and have not found anything similar enough to what I am working with that works. I have tried setting the default in the Get Tasks section by modifying isTaskInProgress('No'), but this only locked the modal and I couldn't modify the option. I have tried setting the default inside the isTaskInProgress function; however, this only worked when the button was clicked, it failed to set a default. I tried seeing if data-ng-default would work; however, this didn't seem to be a recognized parameter. Does anyone have suggestions on how to modify this to get the desired results? Thank you all in advance for your help

Small Disclaimer
I am taking the liberty of assuming you are using UI Bootstrap (since I see bootstrap classes in your sample HTML), so will be using Uib Modal in my example.
Bootstrap Modal docs: https://angular-ui.github.io/bootstrap/#!#modal
Resolver / Callback Solution
You will most likely want to use the controller to set your tr.isTaskInProgress flag rather than using the ng-init directive (a bit more flexibility / readability).
Set tr.isTaskInProgress to false at the top of your target controller function, then pass its value to your modal as a property in a "Modal Resolve Object".
Bootstrap's explanation of the Resolve Object: https://angular-ui.github.io/bootstrap/#!#ui-router-resolves
Code
function MainController($scope, $uibModal) {
let vm = this;
vm.isTaskInProgress = false;
// When you open the modal, pass in the isTaskProgress value
let modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html', // Points to the script template
controller: 'ModalController', // Points to the controller
controllerAs: 'mc',
windowClass: 'app-modal-window',
backdrop: 'static',
resolve: {
isTaskInProgress: function() {
// pass the task state to the Modal
return vm.isTaskInProgress;
}
}
});
// handle the value(s) passed back from the modal
modalInstance.result.then(returnedTaskState => {
// reassign the returned value of the modal
if (returnedTaskState !== null) {
vm.isTaskInProgress = returnedTaskState;
}
});
}
Working Example
https://plnkr.co/ryK7rG
In the interest of time, I've changed some of the variable / method names from what you have in your snippets. In the example, you can...
Set the In Progress value before you open the modal and the modal reflects the In Progress value.
Change the In Progress value inside the modal. On closing the modal, the value will be updated in the main page.
SO Snippet
I realize the SO Snippet window is not exactly the best place for this example, but just tossing my example code in here in case Plunker is inconvenient for some reason.
(function() {
"use strict";
let app = angular
.module("myApp", ["ui.bootstrap"])
.controller("MainController", MainController);
MainController.$inject = ["$scope", "$timeout", "$uibModal"];
function MainController($scope, $timeout, $uibModal) {
/**
* John Papa Style Guide
* https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md
* */
let vm = this;
// ==== scoped variables ====
vm.title = "AngularJS - Passing Toggled Values to a Modal"
vm.taskInProgress = false;
vm.taskButtonLocked = false;
// ==== functions hoist ====
vm.beginTask = _beginTask;
function _beginTask() {
vm.modalIsOpen = true;
// do work
openModal();
}
// ==== local functions ====
function openModal() {
// open the modal with configurations
let modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html', // Points to my script template
controller: 'ModalController', // Points to my controller
controllerAs: 'mc',
windowClass: 'app-modal-window',
backdrop: 'static',
resolve: {
taskInProgress: function() {
// pass the task state to the Modal
return vm.taskInProgress;
}
}
});
// handle the value(s) passed back from the modal
modalInstance.result.then(returnedTaskState => {
// reset control values after modal is closed
vm.taskButtonLocked = false;
vm.modalIsOpen = false;
// reassign the returned value of the modal
console.log("returnedTaskState: ", returnedTaskState);
if (returnedTaskState !== null) {
vm.taskInProgress = returnedTaskState;
}
});
}
}
})();
(function() {
'use strict';
angular
.module('myApp')
.controller('ModalController', ModalController);
ModalController.$inject = ['$scope', '$timeout', '$uibModalInstance', 'taskInProgress'];
function ModalController($scope, $timeout, $uibModalInstance, taskInProgress) {
// Assign Cats to a Modal Controller variable
let vm = this;
vm.inProgress = taskInProgress;
console.log("taskInProgress", taskInProgress)
$scope.submit = function() {
$uibModalInstance.close(vm.inProgress);
}
$scope.close = function() {
$uibModalInstance.close(null);
}
}
})();
input[type="radio"]:hover {
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunk</title>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!-- JQuery and Bootstrap -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Angular Stuff -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.js"></script>
<!-- UI Bootstrap Stuff -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>
<!-- Our Angularjs App -->
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="myApp" ng-controller="MainController as tr">
<!-- ==== MAIN APP HTML ==== -->
<div class="container" style="padding:1em;">
<div class="row">
<div class="col-xs-12">
<div class="jumbotron text-center">
<h2>{{ tr.title }}</h2>
<h4><em>SO Question #55362380</em></h4>
<h4><em>AngularJS - v1.7.8</em></h4>
</div>
</div>
<div class="col-xs-12">
<form>
<div class="form-group">
<h3>Task In Progress</h3>
<div>
<label>Yes:</label>
<input type="radio"
ng-checked="tr.taskInProgress"
ng-click="tr.taskInProgress = true"
ng-disabled="tr.modalIsOpen">
</div>
<label>No:</label>
<input type="radio"
ng-checked="!tr.taskInProgress"
ng-click="tr.taskInProgress = false"
ng-disabled="tr.modalIsOpen">
</div>
<div class="form-group">
<label>Open the modal:</label>
<button type="button"
class="btn btn-success"
ng-click="tr.beginTask();"
ng-disabled="tr.taskButtonLocked">
<span>Begin Task</span>
</button>
</div>
</form>
</div>
</div>
</div>
<!-- ==== MODAL HTML TEMPLATE ==== -->
<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">
<form>
<div class="form-group">
<label>Task State:</label>
<div style="padding:1em;background:rgba(200, 214, 229,0.3);">
<p>
<span ng-show="!mc.inProgress">
<span>Task is not in progress... </span>
<i class="fa fa-check-square" aria-hidden="true"></i>
</span>
<span ng-show="mc.inProgress">
<span>Task is in progress... </span>
<i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
</span>
</p>
</div>
</div>
<div class="form-group" style="padding-top:1em;">
<h3>Task In Progress</h3>
<div>
<label>Yes:</label>
<input type="radio"
ng-checked="mc.inProgress"
ng-click="mc.inProgress = true">
</div>
<label>No:</label>
<input type="radio"
ng-checked="!mc.inProgress"
ng-click="mc.inProgress = false">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="submit()">OK</button>
<button class="btn btn-warning" type="button" ng-click="close()">Cancel</button>
</div>
</script>
</body>
</html>

Related

How to get selected option in be selected in a dropdown after opening a modal in AngularJS?

I have a select tag like this:
<select... ng-model="someProperty" ng-change="openSomeDialog()">
<option value=""></option>
<option value="Test1">Test1</option>
<option value="Test2">Test2</option>
</select>
The openSomeDialog() function opens a ui.bootstrap.modal directive modal. When the user closes the modal, the dropdown reverts to the initial option which is the empty one (first option) instead of what the user has selected. I also tried to use a watch on the select's ngModel and I get the same issue.
If I put some non modal related logic in the function instead of opening a modal, the selection works fine so it seems the process of opening the modal changes the events workflow or something.
How do I get the dropdown to select what the user has selected before the modal opened, after the modal closes?
I think this might be useful-> https://stackoverflow.com/a/1033982/7192927
Try binding the "selected" attribute to an object/variable as required to your case.
If you are using AngularJS, Instead of using select, you can use md-select of angular material, where u have the trackby attribute to make the option appear
as selected.--> https://material.angularjs.org/latest/api/directive/mdSelect
Ng-Options
Try using ng-options:
// Script
$scope.datarray = ["test1, "test2"];
<!-- HTML -->
<select class="form-control" ng-options="test in dataArray" ng-model="someProperty" ng-change="openSomeDialog()">
<option value=""></option>
</select>
https://embed.plnkr.co/wF3gc5/
EDIT: Updated my answer to better align with your requirements / comment.
Reference
https://docs.angularjs.org/api/ng/directive/select
Snippet
(function() {
"use strict";
var app = angular.module('plunker', ['ui.bootstrap']);
app
.controller("MainCtrl", MainCtrl)
.controller("ModalController", ModalController);
MainCtrl.$inject = ["$scope", "$log", "$uibModal"];
function MainCtrl($scope, $log, $uibModal) {
// Sample Data
$scope.cats = [{
id: 0,
name: "mister whiskers"
}, {
id: 1,
name: "fluffers"
}, {
id: 2,
name: "captain longtail"
}];
$scope.openModal = function() {
// Open the modal with configurations
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html', // Points to my script template
controller: 'ModalController', // Points to my controller
controllerAs: 'mc',
windowClass: 'app-modal-window',
resolve: {
cats: function() {
// Pass the Cats array to the Modal
return $scope.cats;
},
selectedCat: function() {
// Pass the selected cat to the Modal
return $scope.selectedCat;
}
}
});
// Handle the value passed back from the Modal
modalInstance.result.then(function(returnedCat) {
if (returnedCat === null || returnedCat === undefined) {
// Do Nothing
return;
}
// We can now update our main model with the modal's output
$scope.selectedCat = returnedCat;
});
}
}
ModalController.$inject = ['$scope', '$timeout', '$uibModalInstance', 'cats', 'selectedCat'];
function ModalController($scope, $timeout, $uibModalInstance, cats, selectedCat) {
// Assign Cats to a Modal Controller variable
console.log("cats: ", cats)
$scope.modalCats = cats;
if (selectedCat !== null || selectedCat !== undefined) {
$scope.selectedModalCat = selectedCat;
}
$scope.submit = function() {
// Pass back modified resort if edit update successful
$uibModalInstance.close($scope.selectedModalCat);
}
$scope.close = function() {
// Pass back modified resort if edit update successful
$uibModalInstance.close(null);
}
}
})();
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css" />
<link data-require="bootstrap-css#3.*" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" />
<!-- JQuery and Bootstrap -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Angular Stuff -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular-touch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular-animate.js"></script>
<!-- UI Bootstrap Stuff -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>
<!-- OUR Stuff -->
<script src="app.js"></script>
<script src="modalController.js"></script>
</head>
<body ng-controller="MainCtrl">
<!-- ==== MAIN APP HTML ==== -->
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="jumbotron text-center">
<h3>AngularJS - ngOptions and UI Bootstrap Modal</h3>
</div>
</div>
<div class="col-xs-12">
<form class="form">
<div class="form-group">
<label class="form-label">Select Profile:</label>
<select class="form-control" ng-options="cat.name for cat in cats track by cat.id" ng-model="selectedCat" ng-change="openModal()">
<option value="">-- Cat Selection --</option>
</select>
</div>
<div class="well form-group" ng-show="selectedCat !== undefined && selectedCat !== null">
<label>Selected: </label>
<pre>{{ selectedCat }}</pre>
</div>
</form>
</div>
</div>
</div>
<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">
<select class="form-control" ng-options="modalCat.name for modalCat in modalCats track by modalCat.id" ng-model="selectedModalCat">
<option value="">-- Cat Selection --</option>
</select>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="submit()">OK</button>
<button class="btn btn-warning" type="button" ng-click="close()">Cancel</button>
</div>
</script>
</body>
</html>
Actually I have found the issue in 'my' code. After closing the modal, it was retrieving data that caused the property bound to the select to refresh as well.
Angular Bootstrap modal Doesn't save the state when the it's closed. You must perform some alternative code to save the user state when they closed the browser or store it in cookie. After that when the user open again the modal you must fetch it and display it in your
<select....... ng-change="openSomeDialog()">...</select>

Angular Wiring up two controllers from Model to auto fill form

I've got an angular app I'm working on where I'm trying to auto fill a pop up modal based on a user's selection.
I thought I could use my model service to keep track of what the user selected and 'wire' the controller for the <select> list and it's edit button to the model but that doesn't seem to work.
Adding to the complexity I'm using angular-route and my <select> list is buried in a view. I was trying to keep my pop up modals in a separate controller outside the view because they've got their own templates and I had problems when I nested them into the view...
I've seen a few examples of wiring up angular apps and thought I understood them but I can't figure out what I'm doing wrong.
EDIT (thanks Pankaj Parkar for pointed out my mistakes in the plunker):
I have a plunker here:
https://plnkr.co/edit/6f9FZmV8Ul6LZDm9rcg9?p=preview
Below is the snipped in a single HTML page with CDN links :).
Am I just completely misunderstanding how angularjs is suppose to work?
<html ng-app="myApp">
<head>
<title>Bootstrap 3</title>
</head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<body>
<div ng-view></div>
<script id="editables.html" type="text/ng-template">
<div class="container">
<div class="jumbotron">
<form>
<div class="form-group">
<select class="form-control" id="mapsSelect" size="10" multiple ng-model="model.selected">
<option ng-repeat="n in editables">{{n}}</option>
<select>
</div>
<a href="#editModal" class = "btn btn-info" data-toggle="modal" ng-click="edit()" >Edit</a>
</form>
</div>
</div><!--end container div-->
</script>
<div ng-controller="modalsController">
<div id="editModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4>New Map</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="name" class="col-lg-3 control-label">Name</label>
<div class="col-lg-9">
<input type="text" class="form-control" id="name" ng-model="formModel.name"></input>
</div>
</div>
<div class="form-group">
<label for="desc" class="col-lg-3 control-label">Description</label>
<div class="col-lg-9">
<input type="text" class="form-control" id="desc" ng-model="formModel.desc"></input>
</div>
</div>
<div class="modal-footer">
<pre> {{ formModel | json }}<br><br>Working: {{ workingMap }}</pre>
Cancel
Continue
</div>
</form>
</div>
</div>
</div><!-- end modal -->
</div>
</body>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- <script src = "js/script.js"></script> -->
<script>
var app = angular.module('myApp', ['ngRoute']);
var modelService = function ($log){
var moduleHello = function(myMessage){
console.log("Module hellow from myService " + myMessage);
}
var moduleNames = {
"First" : {desc: "First's Description"},
"Second" : {desc: "Second's Description"},
"Third" : {desc: "Third's Description"}
};
var moduleWorkingName = {};
return {
hello: moduleHello,
editables: moduleNames,
workingName: moduleWorkingName
}
}//end modelService
app.factory("modelService", ["$log", modelService]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/editables', {
controller: "editablesController",
templateUrl: "editables.html"
}).
otherwise({
redirectTo: "/editables"
});
}]);
app.controller('editablesController', ['$scope', '$log','modelService', function($scope,$log, $modelService) {
$scope.model = {};
//console.log( JSON.stringify( $modelService.editables ) );
$scope.editables = [];
for ( name in $modelService.editables){
$scope.editables.push( name );
}
$scope.edit = function(){
if ( typeof $modelService.editables [$scope.model.selected] != 'undefined'){
$modelService.workingName = $modelService.editables [$scope.model.selected];
console.log ("Setting my working name to " + JSON.stringify( $modelService.workingName ) );
}else{
console.log ("Nothing Selected");
}
}
}]);
app.controller('modalsController', ['$scope','modelService', function($scope,$modelService) {
$scope.formModel = {};
$scope.formModel.name = "Hard coding works of course";
$scope.formModel.desc = $modelService.workingName.desc; //But I can't seem to get this to update. I thought pointing it at an object in the Model would be enough.
console.log("Firing up modalsController");
}]);
</script>
</html>
I spent the last two days mulling over this in my head and I think I figured it out. For starters, here's the (working) plunker:
https://plnkr.co/edit/Kt3rebPtvGTt0WMXkQW4?p=preview
Now, the explanation. I was trying to keep a separate 'formModel' object that kept track of the controller's state. But that's both silly and pointless.
Instead what you're supposed to do is:
a. Create an object in your service to hold all your data (I just called this 'model')
b. For each controller that needs to share data create a variable on the $scope of the controller and point it to your 'model' variable from your service.
c. after that use the variables from your model in your html.
So in both my controllers you'll find this line:
$scope.model = $modelService.model;
and in my HTML you'll find stuff like this:
<input type="text" class="form-control" id="name" ng-model="model.workingName.name"></input>
notice how I'm using "model.workingName.name"? This references $scope.model.workingName.name, which thanks to the line $scope.model = $modelService.model from my JavaScript now points directly to my model.
And that is how you "wire up" Angular.
By the way, experienced Angular folks have probably noticed that this part:
$scope.editables = [];
for ( name in $modelService.model.names){
$scope.editables.push( name );
}
probably belongs in a directive instead of a controller because I'm editing the DOM.
Stuff like that's what makes it so hard to learn AngularJS. There's so many concepts to get the hang of.

How to replace text on field after click Angular?

I have HTML code with inline element:
<span class="title" ng-click="update()">Rock</span>
How to replace this element on input element after click for edit?
And then after push enter on input return back span element?
I tried with directives ng-hide(), ng-show(). But I wonder
You can use either
<span class="title" ng-hide="isEdited" ng-click="update()">Rock</span>
or
<span class="title" ng-show="!isEdited" ng-click="update()">Rock</span>
or even
<span class="title" ng-if="!isEdited" ng-click="update()">Rock</span>
In any case you will want to reference something that can be truthy. For example in your controller you would have something like this in your function
/*the init function just makes sure that everything is setup
and nothing caries over from any local storage or anything
else you may be using*/
init();
init function(){
$scope.isEdited = false;
}
$scope.update = function(){
$scope.isEdited = true;
}
What you need to do is set a variable that contains the state;
<html>
<body ng-app="app">
<div ng-controller="mainController as $ctrl">
<span ng-if="!$ctrl.isInEditMode" class="title" ng-click="$ctrl.update()" ng-bind="$ctrl.spanText"></span>
<div ng-if="$ctrl.isInEditMode">
<input type="text" placeholder="Value for rock" ng-model="$ctrl.spanText" />
<button ng-click="$ctrl.update()">Done</button>
</div>
</body>
</html>
angular.module('app', [])
.controller('mainController', function($scope) {
this.isInEditMode = false;
this.spanText = 'Rock';
this.update = (function() {
this.isInEditMode = !this.isInEditMode;
}).bind(this);
});
I have prepared a Codepen that shows an possible solution: http://codepen.io/stefferd/pen/QdQrrv

Angular UI: field entered in Modal is undefined in controller

Please run this plunker, if you enter a value in the modal and then click on show value, the value is undefined in $scope, how to get the value?
HTML
<div ng-app="app" ng-controller="myCtl">
<input type="button" ng-click="openModal()" value="Open Modal">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h4 class="modal-title">The Title</h4>
</div>
<form name="myForm" novalidate>
Enter a value <input type="text" ng-model="someField" />
</form>
<div class="modal-footer">
<button ng-click="showValue()">Show value</button>
</div>
</script>
</div>
Javascript
var app = angular.module('app', ['ui.bootstrap']);
app.controller('myCtl', function($scope,$uibModal) {
$scope.openModal = function() {
$scope.modalInstance = $uibModal.open({
animation: false,
templateUrl: 'myModalContent.html',
scope: $scope
});
};
$scope.showValue = function() {
alert('value entered=' + $scope.someField);
};
});
You are seeing this because the scope of the modal is isolated. Even though you pass the $scope to modal. It still does not use the same $scope.
For your example the following would work.
Update the modal template:
<button ng-click="showValue(someField)">Show value</button>
Update your controller showValue method as follows:
$scope.showValue = function(theValue) {
$scope.someField = theValue;
alert('value entered=' + $scope.someField);
};
Really though the best way to use the modal is to use the modal instance created by the open method to track the close and dismiss events and handle the result that way. Take a look at the example on on the ui-modal section of the ui-bootstrap documentation

How to transclude content in ui bootstrap modal directive

I've made a custom directive on top of ui bootstrap modal directive so I can use the same modal template everywhere in my app.
My directive works until I try to transclude its content into the template:
http://plnkr.co/edit/YPESA3?p=preview
From index.html
<div ng-controller="ModalDemoCtrl">
<button class="btn" ng-click="open()">Open me!</button>
<my:modal open="shouldBeOpen" close="close()">
<h1>Content</h1>
</my:modal>
</div>
Module code:
angular.module('plunker', ['ui.bootstrap'])
.controller('ModalDemoCtrl', function($scope) {
$scope.open = function () {
$scope.shouldBeOpen = true;
};
$scope.close = function () {
$scope.closeMsg = 'I was closed at: ' + new Date();
$scope.shouldBeOpen = false;
};
$scope.items = ['item1', 'item2'];
})
.directive('myModal', function() {
return {
restrict : 'E',
templateUrl: 'myTpl.html',
//transclude: true,
scope : {
open : '=',
close : '&'
}
};
});
Modal template:
<div modal="open">
<div class="modal-header">
<h4>I'm a modal!</h4>
</div>
<div class="modal-body">
<!--<div ng-transclude/>-->
</div>
<div class="modal-footer">
<button class="btn btn-warning cancel" ng-click="close()">Cancel</button>
</div>
</div>
Uncomment transclude property from the directive and the template and you'll see you get a TypeError: undefined is not a function.
I can't figure what I'm doing wrong.
OP, your snippet is exactly what I was looking to do—thanks!
I managed to get your plunk working by passing replace:true as well as transclude: true
Here's the updated plunk http://plnkr.co/edit/gxCS2V?p=preview
I'm new to Angular, so I was interested to know why:
replace - if set to true then the template will replace the current element, rather than append the template to the element.
(via the Angular docs)
Which, of course makes sense once you know.
Good to know if you want to make your directive especially recyclable. Modals are pretty perfect example.
Related : ui-bootstrap is worth checking out.
Check this solution, you dont need a extra controller or angular-ui for that only pass a simple handler and use it
example.js
angular.module('plunker', [], function() {
})
.directive('modal', function() {
return {
restrict : 'E',
templateUrl: 'myTpl.html',
transclude: true,
controller: function($scope) {
// you need get a better unique generator
$scope.modal_id = 'modal_' + Math.floor((Math.random()*100+1));
$scope.handler = $scope.modal_id;
},
scope : {
handler : '='
}
};
})
.run();
index.html
<!doctype html>
<html ng-app="plunker">
<head>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div ng-init="handler = null">
<modal handler="handler">
<h1>Content</h1>
</modal>
Open me
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
<script src="example.js"></script>
</body>
</html>
myTpl.html
<div id="{{modal_id}}" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="{{modal_id}}Label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="{{modal_id}}Label">I'm a modal!</h4>
</div>
<div class="modal-body">
<div ng-transclude></div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
</div>
</div>
look how works in plunker

Resources