How to use multiple ng-app and add new modal - javascript

Here is my todo.js file
//let example = angular.module("example", ["ngStorage"]);
example.controller("ExampleController", function($scope, $localStorage) {
$scope.save = function() {
let testObject = [
{
name:"aaa",
lastName:"bbb"
},
{
name:"ccc",
lastName:"ddd"
}
]
let myVal = $localStorage.myKey;
$localStorage.$reset();
if(!myVal){
console.log("okey");
$localStorage.myKey = testObject;
} else {
myVal.push({
name:"fff",
lastName:"ggg"
})
$localStorage.myKey = myVal;
}
$scope.datas = $localStorage.myKey;
}
$scope.load = function() {
console.log($localStorage.myKey)
}
});*/
var app = angular.module("modalFormApp", ['ui.bootstrap']);
app.controller("modalAccountFormController", function ($scope, $modal, $log) {
$scope.showForm = function () {
$scope.message = "Show Form Button Clicked";
console.log($scope.message);
var modalInstance = $modal.open({
templateUrl: 'modal.html',
controller: ModalInstanceCtrl,
scope: $scope,
resolve: {
userForm: function () {
return $scope.userForm;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
var ModalInstanceCtrl = function ($scope, $modalInstance, userForm) {
$scope.form = {}
$scope.submitForm = function () {
if ($scope.form.userForm.$valid) {
console.log('user form is in scope');
$modalInstance.close('closed');
} else {
console.log('userform is not in scope');
}
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
And here is my index.html file:
<html>
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="../node_modules/angular-1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.10/ngStorage.min.js"></script>
<script src="./todo.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.9.0.js"></script>
</head>
<body>
<!--<div ng-app="example">
<div ng-controller="ExampleController">
<button ng-click="save()">Save</button>
<button ng-click="load()">Load</button>
<br>
<input type='text' ng-model='searchText' placeholder="Search..." />
<ul>
<li ng-repeat="data in datas | filter:searchText">
{{data.name}}
</li>
</ul>
</div>
</div>-->
<div ng-app="modalFormApp">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<!-- PAGE HEADER -->
<div class="page-header">
<h1>AngularJS Form Validation</h1>
</div>
<div ng-controller="modalAccountFormController">
<div class="page-body">
<button class="btn btn-primary" ng-click="showForm()">Create Account</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Lastly here is my modal.html:
<div class="modal-header">
<h3>Create A New Account!</h3>
</div>
<form name="form.userForm" ng-submit="submitForm()" novalidate>
<div class="modal-body">
<!-- NAME -->
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="name" required>
<p ng-show="form.userForm.name.$invalid && !form.userForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<!-- USERNAME -->
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8" required>
<p ng-show="form.userForm.username.$error.minlength" class="help-block">Username is too short.</p>
<p ng-show="form.userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
</div>
<!-- EMAIL -->
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="email" required>
<p ng-show="form.userForm.email.$invalid && !form.userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-disabled="form.userForm.$invalid">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</form>
I'm trying to open a modal when i click the button. I made comment line the other part which i'm using but it works fine. The second part is for only the modal but it is not working. I even can not open the modal. If there is a basic way to do this can you share with me? I only need to open this modal. I can handle the rest of it.

From the Docs:
There are a few things to keep in mind when using ngApp:
only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead.
For more information, see
AngularJS ng-app Directive API Reference

Related

how to pass an array/json values to a select on an angularjs modal

I'm pretty sure this is very simple problem to solve, but I'm stuck. I have a modal angularjs which opens a form which has a Select element and others which needs to be populated using Array/JSON values. For some how, I am stuck passing these values from either the ModalForm controller, or main page controller. I have created this Plunker which recreates the problem.
The main page code is:
angular.module('ui.bootstrap.demo', ['ngAnimate', '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.open = function() {
var modalInstance = $uibModal.open({
animation: $ctrl.animationsEnabled,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'rostaDetail.html',
controller: 'ModalInstanceCtrl',
controllerAs: '$ctrl',
resolve: {
items: function() {
return $ctrl.items;
}
}
});
modalInstance.result.then(function(selectedItem) {
$ctrl.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
// 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');
};
});
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-animate.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">
<div ng-controller="ModalDemoCtrl as $ctrl" class="modal-demo">
<button type="button" class="btn btn-default" ng-click="$ctrl.open()">Open me!</button>
<div ng-show="$ctrl.selected">Selection from a modal: {{ $ctrl.selected }}</div>
<div class="modal-parent">
</div>
</div>
Open me!
Selection from a modal: {{ $ctrl.selected }}
And the modal form is:
<!-- .Modal Form Edit Rosta -->
<div class="modal-header">
<h3 class="modal-title" id="modal-title">Edit Roster</h3>
</div>
<div class="modal-body" id="modal-body">
<form class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="selectDuty">Select Duty</label>
<div class="col-md-4">
<select id="selectDuty" name="selectDuty" ng-model="item" ng-options='item in items' class="form-control"></select>
</div>
</div>
<!-- Multiple Checkboxes -->
<div class="form-group">
<label class="col-md-4 control-label" for="checkboxes">Multiple Checkboxes</label>
<div class="col-md-4">
<div class="checkbox">
<label for="checkboxes-0">
<input name="checkboxes" id="checkboxes-0" value="1" type="checkbox">
Option one
</label>
</div>
</div>
</div>
<div class="modal-footer">
<!-- Button (Double) -->
<div class="form-group">
<!-- <label class="col-md-4 control-label" for="button1id">Double Button</label> -->
<div class="col-md-8">
<button id="buttonSave" name="buttonSave" class="btn btn-primary" ng-click="$ctrl.ok()">Save</button>
<button id="buttonDelete" name="buttonDelete" class="btn btn-danger" ng-click="$ctrl.delete()" ng-show="false">Delete</button>
<button type="button" class="btn btn-basic" ng-click="$ctrl.cancel()">Cancel</button>
</div>
</div>
</div>
</fieldset>
</form>
</div>
As you used controllerAs syntax so for access objects or functions in scope you should use controllerAs variable and . . here $ctrl.
It should be like this.
ng-options='item as item for item in $ctrl.items'
and in controller:
$ctrl.ok = function () {
$ctrl.selected = {
item: $ctrl.item
};
$uibModalInstance.close($ctrl.selected.item);
};
Demo

Controller reading component data

My idea is to create a big form from separated components. So this is my main template:
<form novalidate>
<div class="row">
<user></user>
</div>
<button type="button" class="btn btn-default" ng-click="submit()"> Submit </button>
</form>
and its controller (the template is binded from ui route config to the controller)
(function () {
'use strict';
angular.module('app')
.controller('formCtrl', formCtrl);
function formCtrl ($scope) {
$scope.submit = function() {
console.log("read data");
}
}
})();
Now, the user component:
(function () {
'use strict';
var module = angular.module('app.user');
module.component("user", {
templateUrl: "app/user/user.html",
controllerAs: "model",
controller: function () {
var model = this;
model.user = {};
}
});
})();
and the user template:
<form novalidate>
<form-group>
<label for="inputUser"> Name <label>
<input ng-model="model.user.name" id="inputUser" type="text" placeholder="User"/>
</form-group>
<form-group>
<label for="inputUser"> Email <label>
<input ng-model="model.user.email" id="inputUser" type="email" placeholder="Email"/>
</form-group>
<div>
{{model.user | json}}
</div>
</form>
Now I want to be able to read user data when the user do the submit. How can I do it?
When using components, depending on the type of component (smart or dumb), you have to emit an output to the parent controller to handle such thing. But in this case, you can use ngModel to handle a model and change it on the parent from within the component. For example:
Working snippet:
angular.module('app', [])
.controller('formCtrl', function($scope) {
$scope.user = {};
$scope.submit = function() {
console.log($scope.user);
}
})
.component("user", {
bindings: {
user: '=ngModel'
},
templateUrl: "app/user/user.html",
controllerAs: "model",
controller: function() {}
});
angular.element(function() {
angular.bootstrap(document, ['app']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<form novalidate ng-controller="formCtrl">
<div class="row">
<user ng-model="user"></user>
</div>
<button type="button" class="btn btn-default" ng-click="submit()">Submit</button>
</form>
<script type="text/ng-template" id="app/user/user.html">
<form novalidate>
<div>
<label for="inputUser">Name
<label>
<input ng-model="model.user.name" id="inputUser" type="text" placeholder="User" />
</div>
<div>
<label for="inputUser">Email
<label>
<input ng-model="model.user.email" id="inputUser" type="email" placeholder="Email" />
</div>
<div>
{{ model.user | json }}
</div>
</form>
</script>
A possible solution would be $$childTail. So if I want to access to user:
$scope.$$childTail.model.user

Argument 'myController' is not a function, got undefined

I'm trying to setup some controllers in my angular app but I'm not sure why I can't make them working, since I think I'm using similar approach as I've done before.
I declared app.js file:
'use strict';
var modules = [
'app.controllers',
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ui.router',
'LocalStorageModule',
'angular-loading-bar'
];
var app = angular.module('app', modules);
app.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
})
app.factory('forgotPasswordService', ['$http', function ($http) {
var fac = {};
fac.forgotPassword = function (forgotPasswordData) {
return $http.post('/api/Account/ForgotPassword', forgotPasswordData)
};
return fac;
}])
app.factory('signUpService', ['$http', function ($http) {
var signUpServiceFactory = {};
signUpServiceFactory.saveRegistration = function (registration) {
return $http.post('/api/account/register', registration);
};
return signUpServiceFactory;
}]);
Then controllers.js file with this content:
angular.module('app.controllers', [])
.controller('signupController', [
'$scope', '$window', 'signUpService',
function($scope, $window, signUpService) {
$scope.init = function() {
$scope.isProcessing = false;
$scope.RegisterBtnText = "Register";
};
$scope.init();
$scope.IsLimitedCompany = null;
$scope.registration = {
Email: "",
Password: "",
ConfirmPassword: ""
};
$scope.signUp = function() {
$scope.isProcessing = true;
$scope.RegisterBtnText = "Please wait...";
signUpService.saveRegistration($scope.registration).then(function(response) {
alert("Registration Successfully Completed. Please sign in to Continue.");
$window.location.href = "login.html";
}, function() {
alert("Error occured. Please try again.");
$scope.isProcessing = false;
$scope.RegisterBtnText = "Register";
});
};
}
]);
And my html file:
<!DOCTYPE html>
<!--[if !IE]><!-->
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<script src="/Metronic/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-cookies.min.js"></script>
<script src="/Scripts/angular-resource.min.js"></script>
<script src="/Scripts/angular-sanitize.min.js"></script>
<script src="/Scripts/angular-route.min.js"></script>
<script src="/Scripts/angular-ui-router.min.js"></script>
<script src="/Angular/app.js"></script>
<script src="/Angular/controllers.js"></script>
<script src="/Scripts/angular-local-storage.min.js"></script>
<script src="/Scripts/loading-bar.min.js"></script>
<script src="/Angular/Services/authInterceptorService.js"></script>
</head>
<body class="login">
<div class="content" ng-app="app">
<!-- BEGIN REGISTRATION FORM -->
<div class="register-form" ng-controller="signupController">
<h3 class="font-green">Sign Up</h3>
<p class="hint"> Enter your account details below: </p>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Email</label>
<input class="form-control placeholder-no-fix" ng-model="registration.Email" type="text" autocomplete="off" placeholder="Email" name="username" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control placeholder-no-fix" ng-model="registration.Password" type="password" autocomplete="off" id="register_password" placeholder="Password" name="password" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Re-type Your Password</label>
<input class="form-control placeholder-no-fix" ng-model="registration.ConfirmPassword" type="password" autocomplete="off" placeholder="Re-type Your Password" name="rpassword" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Role</label>
<select name="role" ng-change="CheckRole()" ng-model="registration.Role" class="form-control">
<option value="">Role</option>
<option value="Borrower">Borrower</option>
<option value="Introducer">Introducer</option>
<option value="Investor">Investor</option>
<option value="Valuer">Valuer</option>
</select>
</div>
<div class="form-actions">
<button type="button" id="register-back-btn" class="btn green btn-outline">Back</button>
<button type="submit" id="register-submit-btn" class="btn btn-success uppercase pull-right" ng-click="signUp()" ng-disabled="isProcessing" value="{{RegisterBtnText}}">
Submit
</button>
</div>
</div>
<!-- END REGISTRATION FORM -->
</div>
</body>
</html>
Any idea what am I missing?
I'm getting this error:
Error: [ng:areq] Argument 'signupController' is not a function, got undefined
You have included JS file in wrong order.
Currently it is
<script src="/Angular/app.js"></script>
<script src="/Angular/controllers.js"></script>
Because of this your app.js not getting the defination of app.controllers.
Its should be like this one
<script src="/Angular/controllers.js"></script>
<script src="/Angular/app.js"></script>

Sharing data between different controllers

I want to build a small application (for learning Angular JS) that can define a list of locations and a list of events. The application was developed based on the tutorial found here: http://g00glen00b.be/prototyping-spring-boot-angularjs/.
When defining a new event I would like to associate a location for the new event. The location should be selected using a combobox.
So first I define 2 locations, let's say Location 1 and Location 2. I want to bind somehow the list of available locations (1 and 2) to the combobox labeled "Location select" see this image
So far I was able to bind the location list to the combobox, but the items of the combobox are updated only when I refresh the browser. I would like to be able to automatically refresh the content of the combobox whenever the list of available locations is changed (a new location is added or a location is removed).
Here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet"
href="./bower_components/bootstrap-css-only/css/bootstrap.min.css" />
</head>
<body ng-app="myEventApp">
<div class="container" ng-controller="EventAppController" >
<div class="page-header">
<h1>Edit Events</h1>
</div>
<div class="alert alert-info" role="alert"
ng-hide="events && events.length > 0">There are no events yet.
</div>
<form class="form-horizontal" role="form"
ng-submit="addEvent(newEventName,newEventDescription)" ng-controller="LocationAppController">
<div >Locations: {{locations}}</div>
<div class="form-group" ng-repeat="event in events">
<div class="checkbox col-xs-9">
<label> <strong>{{event.name}}</strong> /
{{event.description}}
</label>
</div>
<div class="col-xs-3">
<button class="pull-right btn btn-danger" type="button"
title="Delete" ng-click="deleteEvent(event)">
<span class="glyphicon glyphicon-trash"></span>
</button>
</div>
</div>
<hr />
<div class="input-group">
<input type="text" class="form-control" ng-model="newEventName"
placeholder="Enter the name..." /> <input type="text"
class="form-control" ng-model="newEventDescription"
placeholder="Enter the description..." />
<label for="locationSelect">Location select: </label>
<select
name="locationSelect" id="locationSelect" ng-model="data.repeatSelect">
<option value="">---Please select---</option>
<option ng-repeat="location in locations"
value="{{location.id}}">{{location.name}}</option>
</select>
<div class="col-md-6"></div>
<span class="input-group-btn">
<button class="btn btn-default" type="submit"
ng-disabled="!newEventName||!newEventDescription" title="Add">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</form>
</div>
<!-- Location -->
<div class="container" ng-controller="LocationAppController">
<div class="page-header">
<h1>Edit Locations</h1>
</div>
<div class="alert alert-info" role="alert"
ng-hide="locations && locations.length > 0">There are no
locations defined yet.</div>
<form class="form-horizontal" role="form"
ng-submit="addLocation(newLocationName,newLocationAddress)">
<div class="form-group" ng-repeat="location in locations">
<div class="checkbox col-xs-9">
<label> <strong>{{location.name}}</strong> /
{{location.address}}
</label>
</div>
<div class="col-xs-3">
<button class="pull-right btn btn-danger" type="button"
title="Delete" ng-click="deleteLocation(location)">
<span class="glyphicon glyphicon-trash"></span>
</button>
</div>
</div>
<hr />
<div class="input-group">
<input type="text" class="form-control" ng-model="newLocationName"
placeholder="Enter the name..." /> <input type="text"
class="form-control" ng-model="newLocationAddress"
placeholder="Enter the address..." />
<!-- <label>Location: </label> -->
<!-- <select -->
<!-- name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect"> -->
<!-- <option ng-repeat="option in data.availableOptions" -->
<!-- value="{{option.id}}">{{option.name}}</option> -->
<!-- </select> -->
<div class="col-md-6"></div>
<span class="input-group-btn">
<button class="btn btn-default" type="submit"
ng-disabled="!newLocationName||!newLocationAddress" title="Add">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</form>
</div>
<script type="text/javascript"
src="./bower_components/angular/angular.min.js"></script>
<script type="text/javascript"
src="./bower_components/angular-resource/angular-resource.min.js"></script>
<script type="text/javascript"
src="./bower_components/lodash/dist/lodash.min.js"></script>
<script type="text/javascript" src="./app/eventApp.js"></script>
<script type="text/javascript" src="./app/eventControllers.js"></script>
<script type="text/javascript" src="./app/eventServices.js"></script>
<script type="text/javascript" src="./app/locationControllers.js"></script>
<script type="text/javascript" src="./app/locationServices.js"></script>
<script type="text/css" src="./app/custom.css"></script>
</body>
</html>
And these are the controllers used:
eventControllers.js
(function(angular) {
var EventAppController = function($scope, Event) {
Event.query(function(response) {
$scope.events = response ? response : [];
});
$scope.addEvent = function(name, description) {
new Event({
locations:[],
name : name,
description : description,
}).$save(function(event) {
$scope.events.push(event);
});
$scope.newEventName = "";
$scope.newEventDescription = "";
};
$scope.updateEvent = function(event) {
event.$update();
};
$scope.deleteEvent = function(event) {
event.$remove(function() {
$scope.events.splice($scope.events.indexOf(event), 1);
});
};
};
EventAppController.$inject = [ '$scope', 'Event' ];
angular.module("myEventApp.controllers").controller("EventAppController",
EventAppController);
}(angular));
locationControllers.js
(function(angular) {
var LocationAppController = function($scope, Location) {
Location.query(function(response) {
$scope.locations = response ? response : [];
});
$scope.addLocation = function(name, address) {
new Location({
name: name,
address: address,
}).$save(function(location) {
$scope.locations.push(location);
});
$scope.newLocationName = "";
$scope.newLocationAddress = "";
};
$scope.updateLocation = function(location) {
location.$update();
};
$scope.deleteLocation = function(location) {
location.$remove(function() {
$scope.locations.splice($scope.locations.indexOf(location), 1);
});
};
return {
getLocations: function() {
return $scope.locations;
}
}
};
LocationAppController.$inject = ['$scope', 'Location'];
angular.module("myEventApp.controllers").controller("LocationAppController", LocationAppController);
}(angular));
eventServices.js
(function(angular) {
var EventFactory = function($resource) {
return $resource('/event/:id', {
id : '#id'
}, {
update : {
method : "PUT"
},
remove : {
method : "DELETE"
}
});
};
EventFactory.$inject = [ '$resource' ];
angular.module("myEventApp.services").factory("Event", EventFactory);
}(angular));
locationServices.js
(function(angular) {
var LocationFactory = function($resource) {
return $resource('/location/:id', {
id : '#id'
}, {
update : {
method : "PUT"
},
remove : {
method : "DELETE"
}
});
};
LocationFactory.$inject = [ '$resource' ];
angular.module("myEventApp.services").factory("Location", LocationFactory);
}(angular));
So, the question is: how to automatically update the content of the combobox when a new location is added / a location is deleted? Thank you.

Strange behaviour using angular-ui-bootstrap date inside an angular-ui-modal

I am developing my first app using Angular and I can't see what's wrong.
I have used ui-bootstrap date with no issues in other places but then I tried using it inside a modal and whenever you pick a date inside the modal for the first time it works properly but then if you pick the wrong date and want to pick the correct one clicking the button to open the calendar a second time it doesn't work if it's inside the modal.
I have created a plunker sample where the error is reproduced.
Code fragments follows:
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<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" />
<link data-require="bootstrap-theme#3.2.0" data-semver="3.2.0" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css" />
<script data-require="angular.js#1.3.0-beta.5" data-semver="1.2.21" src="https://code.angularjs.org/1.2.21/angular.js"></script>
<script data-require="angular-ui-bootstrap#0.11.0" data-semver="0.11.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<h1>Angular ui date!</h1>
<div ng-controller="DateController">
<div class="row">
<div class="col-md-6">
<h4>Date(This works)</h4>
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="{{format}}" disabled
ng-model="activityDate" is-open="opened" datepicker-options="dateOptions"
ng-required="true" close-text="Close"/>
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)"><i
class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
</div>
<div class="row">
<div class="col-md-6">
<button type="button" class="btn btn-primary" ng-click="openModal()">Open Date Modal</button>
</div>
</div>
</div>
dateModal.html
<div>
<div class="modal-header">
<h3 class="modal-title">Date Modal Sample</h3>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<h4>Modal Date(works only the first time! whyyyyyy?????)</h4>
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="{{format}}" disabled
ng-model="dateModal" is-open="opened"
ng-required="true" close-text="Close"/>
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</p>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</div>
app.js
'use strict';
(function () {
var myApp = angular.module('myApp', ['ui.bootstrap']);
myApp.controller('DateController', ['$scope', '$modal', '$log', function($scope, $modal, $log){
//Initializes date
$scope.today = function () {
$scope.activityDate = new Date();
};
//open calendar to select initial date
$scope.open = function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
$log.info('open function was called');
};
$scope.today();
$scope.format = 'MM/dd/yyyy';
//open modal window
$scope.openModal = function () {
var modalInstance = $modal.open({
templateUrl: 'dateModal.html',
controller: 'DateModalController'
});
}
}]);
myApp.controller('DateModalController', ['$scope', '$modalInstance', function($scope, $modalInstance){
$scope.cancel = function () {
$modalInstance.dismiss('Cancel');
};
//Initializes date
$scope.today = function () {
$scope.dateModal = new Date();
};
//open calendar to select initial date
$scope.open = function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
$log.info('open button from modal calendar field has been pressed!!!!');
};
$scope.today();
$scope.format = 'MM/dd/yyyy';
}]);
})();
Scopes inherit from their parent scopes.
The modal is created as a child of the scope that you passed in when initalising it (or on the $rootScope by default). When attempting to set a property directly on the scope, angular will automatically create it for you. However, if you try doing model.myProperty, if model doesn't exist on the child scope, it will travel up to the parent and correctly set it there (if it exists).
A good description on how scopes work can be found here: https://github.com/angular/angular.js/wiki/Understanding-Scopes
Here is a working sample without having to resort to using $parent.
http://plnkr.co/edit/WeJqirLDOoFuTqJEHEdg
<input type="text" class="form-control" datepicker-popup="{{format}}" disabled
ng-model="dateModal.date" is-open="dateModal.opened"
ng-required="true" close-text="Close"/>
Pretty sure it's related to the modal's scope overriding your scope and $scope.opened in the directive. I'm not sure the exact cause but you can work around it by using is-open="$parent.opened" in your dateModal template.

Categories

Resources