Angular-ui bootstrap- how to display selected input value in a modal? - angularjs

I am new in angular.js. I have to display in a modal the selected value of input, but I don't succeed.
I have the following inputs:
<form>
<input type="radio" name="toggleDiv" value="show" ng-click="show()" checked/> Show Text
<br>
<input type="radio" name="toggleDiv" ng-click="hide()" value="hide"/> Hide Text
</form>
I have to open a popup dialog and display the value of the selected value.
The moodal:
<div class="row" ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
{{ inputsVal }}
</div>
</script>
<button type="button" class="btn btn-default" ng-click="open()">Open me!</button>
</div>
I try the following function:
app.controller('ModalDemoCtrl', function ($scope, $uibModal) {
$scope.open = function () {
$scope.inputsValue=$('input:checked').val()
return $scope.inputsValue
}}
}

your implementation is wrong.check anguar ui bootstrap modal documentation.
You have to do like this
$scope.open = function () {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
items: function () {
return $scope.myForm;
}
}
});
in your controller,
app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
in html,
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
{{ items.input}}
</div>
</script>
<form>
<input type="radio" name="toggleDiv" ng-model="myForm.input" value="show" ng-click="show()" checked/> Show Text
<br>
<input type="radio" name="toggleDiv" ng-click="hide()" value="hide"/> Hide Text
</form>
edit
If you want to work with jquery way then you need to use $apply()
$scope.$apply(function () {
$scope.inputsValue=$('input:checked').val();
});
hope this helps .. :)

Related

How to delay my ng-init function until my api call is success

I am working on dynamic form with ng-repeat. I am using oi-select for loading my location. I am loading this form inside modal popup. Regarding get my location values i am calling one api function on click of my modal open button. On success of this api call i was calling ng-init method. As per my requirement i should make this api call on click of modal open button. If i am clicking that button at first time, by default my first location value is not loaded inside select-box. Because my ng-init function called before my api call. Other than first time its working fine. Only first time it was not loaded that location[0] value defaultly . My question is how to delay this ng-init function?. Is there any other way to resolve this issue. Here i attached my plunker link .Please help me out from this issue. https://plnkr.co/edit/xDVetaZIzpFdKLS9ihU6?p=preview
html code
<body class="container row">
<div ng-app="myApp">
<div ng-controller="myCtrl">
<a class="btn btn-primary" data-toggle="modal" href='#modal-id' ng-click="getLocation()">Trigger modal</a>
<div class="modal fade" id="modal-id">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Location</label>
<oi-select ng-model="user.location" multiple oi-options="v for v in locations" ng-init='initLocation(user, locations)' name="select2" required>
</oi-select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</div>
</div>
js code
var app = angular.module('myApp', ['ngResource', 'oi.select']);
app.factory('commonService', function($http, $q) {
return {
preFCSManualReleases: function() {
var deferred = $q.defer();
var url = "data.json";
$http.get(url, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: ''
}).then(function(data) {
deferred.resolve(data.data);
});
return deferred.promise;
}
}
});
app.controller('myCtrl', function($scope, commonService) {
$scope.getLocation = function() {
$scope.ids = [1, 2];
commonService.preFCSManualReleases().then(function(data) {
$scope.locations = data;
console.log('$scope.location[0]==============>', $scope.locations[0])
$scope.initLocation = (user, locations) => {
if (!user.location.length) {
user.location.push(locations[0]);
}
}
});
$scope.users = $scope.ids.map(function(id) {
return {
id: id,
comment: "",
location: []
};
});
}
$scope.adduser = function() {
var data = $scope.users.map(function(user) {
return {
"userid": user.id,
"manualcomment": user.comment,
"location": user.location
}
});
console.log("data", data)
}
});
You can put a condition on the oi-select parent:
<div class="col-md-3" ng-if="locationsLoaded">
<label>Location</label>
<oi-select ng-model="user.location" multiple oi-options="v for v in locations" ng-init='initLocation(user, locations)' name="select2" required>
</oi-select>
</div>
You can then control the $scope.locationsLoaded in your controller:
$scope.getLocation = function() {
$scope.locationsLoaded = false;
commonService.preFCSManualReleases().then(function(data) {
$scope.locations = data;
console.log('$scope.location[0]==============>', $scope.locations[0])
$scope.initLocation = (user, locations) => {
if (!user.location.length) {
user.location.push(locations[0]);
}
}
$scope.locationsLoaded = true; // we now have the required data
});
}
The ng-if will compile the element once locationsLoaded is true and when the ng-init is triggered, you are sure that there is data.

How to make ng-click working on dynamically added button?

I have an input field. On focus a tooltip popups with a button that was added dynamically. How to make ng-click on that button working?
I was looking for solutions, but there is no any clear concrete example.
here is my plunkr: http://plnkr.co/edit/UFv6qcg68wD99HXf76xP?p=preview
Here is the code:
<body>
<div ng-controller="PopoverDemoCtrl">
<h4>Dynamic</h4>
<p>{{message}}</p>
<br><button class="btn btn-warning" ng-click="removeMessage()">Remove mesage</button>
<br><br>
<input type="text" value="Click me!" uib-popover-html="htmlPopover" popover-trigger="focus" class="form-control">
popover-trigger="focus" class="form-control">-->
</div>
</body>
</html>
controller
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('PopoverDemoCtrl', function ($scope, $sce) {
$scope.dynamicPopover = {
content: 'Hello, World!',
templateUrl: 'myPopoverTemplate.html',
title: 'Title'
};
$scope.message = '';
$scope.showMessage = function(){
console.log("Simple message");
$scope.message = "Just added text";
}
$scope.removeMessage = function(){
console.log("Simple message");
$scope.message = "";
}
$scope.test = function(){
console.log("test me click")
}
$scope.placement = {
options: [
'top',
'top-left',
'top-right',
'bottom',
'bottom-left',
'bottom-right',
'left',
'left-top',
'left-bottom',
'right',
'right-top',
'right-bottom'
],
selected: 'top'
};
$scope.htmlPopover = $sce.trustAsHtml('<button ng-mousedown="test()"><b style="color: red">Add message</b></button> to the <div class="label label-success">page</div> content');
});
Replace uib-popover-html to uib-popover-template and use ng-click instead of ng-mousedown and give little delay to close the popop
<input type="text" ng-model="value" value="{{value}}" uib-popover-template="htmlPopover" popover-trigger="focus" popover-popup-close-delay="1000" class="form-control">
<script type="text/ng-template" id="myPopoverTemplate.html">
<div>
<button ng-click="test()"><b style="color: red">Add message</b></button>
<div class="label label-success">page</div>
</div>
</script>
sample working code.
http://embed.plnkr.co/deN1VjHdXbTKXlqdQ0vt/
More info regarding Uib https://angular-ui.github.io/bootstrap/#/popover
Use uib-popover-template instead of uib-popover-html:
$scope.htmlPopover ='myPopoverTemplate.html';
<input type="text" value="Click me!" uib-popover-template="htmlPopover" popover-trigger="focus" class="form-control">
<script type="text/ng-template" id="myPopoverTemplate.html">
<div>
<button ng-mousedown="test()"><b style="color: red">Add message</b></button>
<div class="label label-success">page</div>
</div>
</script>
http://plnkr.co/edit/ERjqaV3IJEtTPDQv9c0l?p=preview

How to push html element

first, iam using AngularJS v1.3.14
i try to push : label ,input ,button html element
here my html code:
<div class="container" ng-controller="ctrl" >
<div class="form-inline" ng-repeat="c in controls">
<label class="control-label">Name:</label>
<input class="form-control">
<button class="btn btn-danger">X</button>
</div>
<button class="btn btn-primary" ng-click="add();">+</button>
and script code:
angular.module("app", [])
.controller("ctrl", function ($scope) {
$scope.controls=[];
$scope.add = function () {
$scope.controls.push({
...
})
};
});
and my question is: how can i push div with controls id.
try this, you need to dynamically add the html controls in a array then re-rendering the array abject values by using ng-repeat
Html code
<div class="form-inline" ng-repeat="c in controls">
<div ng-bind-html="c.htmlValue | to_trusted"></div>
</div>
<button class="btn btn-primary" ng-click="add();">+</button>
Js Code
angular.module("app", [])
.controller("ctrl", function ($scope) {
$scope.controls=[];
$scope.add = function () {
var stringValue="<label class=\'control-label\'>Name:</label><input class=\'form-control\'><button class=\'btn btn-danger\'>X</button>"
$scope.controls.push({ "htmlValue": stringValue })
};
}).filter('to_trusted', ['$sce', function ($sce) {
return function(text) {
return $sce.trustAsHtml(text);
};
}]);
See this working code in
Plunker
Demo Image
finally i found the solution:
html:
<div class="container" ng-controller="ctrl">
<div class="form-inline" ng-repeat="todo in todos track by $index">
<label class="control-label">Name:</label>
<input type="text" class="form-control" ng-model="todos[$index]">
<button class="btn btn-danger" ng-click="remove($index);">X</button>
</div>
<div class="form-inline">
<button class="btn btn-primary" ng-click="add();">+</button>
</div>
scripts:
angular.module('app', [])
.controller('ctrl', function ($scope) {
$scope.todos = [''];
$scope.add = function () {
$scope.todos.push({});
console.log($scope.todos);
};
$scope.remove = function (index) {
$scope.todos.splice(index, 1);
};
});
hope this help.
The button was not inside the scope of the controller. At the bottom you can find a link with the PLNKR demonstratic a basic use.
angular.module("app", [])
.controller("ctrl", function ($scope) {
$scope.controls=[];
$scope.add = function () {
$scope.controls.push('')
};
});
HTML:
<body ng-app="app">
<div ng-controller="ctrl" >
<div class="container" >
<div class="form-inline" ng-repeat="c in controls">
<label class="control-label">Name:</label>
<input class="form-control" ng-model="c">
<button class="btn btn-danger">X</button>
</div>
</div>
<button class="btn btn-primary" ng-click="add();">+</button>
</div>
</body>
Example

Angular ui modal form not displaying form

For studying angular js, I created an angular application for performing CRUD operation. I wanted to add modal form on my application. So when user click to add an item a modal form popups. For that I used angular ui of bootstrap. I tried to use the code http://plnkr.co/edit/dRahuG?p=preview which is in the ui bootstrap tutorial. It working fine in the plunker but not in application.
<div class="container" ng-controller="ClassController">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<form ng-submit="submit()">
<div class="modal-body">
<label>User name</label>
<input type="text" ng-model="user.user" />
<label>Password</label>
<input type="password" ng-model="user.password" />
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
<input type="submit" class="btn primary-btn" value="Submit" />
</div>
</form>
</script>
<button class="btn" ng-click="open()">Add</button>
<div ng-show="selected">aSelection from a modal: {{ selected }}</div>
</div>
And my controller is
var myApp = angular.module('myApp', ['ui.bootstrap']);
myApp.controller('ClassController',['$scope','$http','$modal','classFactory',function($scope,$http,$modal){
$scope.items = ['item1', 'item2', 'item3'];
$scope.open = function () {
$modal.open({
templateUrl: 'myModalContent.html',
backdrop: true,
windowClass: 'modal',
controller: function ($scope, $modalInstance) {
$scope.submit = function () {
$modalInstance.dismiss('cancel');
}
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
resolve: {
items: function () {
return $scope.items;
}
}
});
};
}])
When I clicked the button the screen get darken but the modal form is not coming. I don't know where I gone wrong. I am using sails.js to load the server. Moreover I am beginner in angular js.

Angular js scope between directive and controllers

I have to show user login page in pop up and have to validate user name and password with the server by using angular js. I create one app model file, and one controller, service and one directive. My code looks like bellow,
app.js
angular.module('mint', ['ngAnimate', 'toastr']);
mycontroller.js
angular.module('mint').controller(
'headercontroller',
[
'$scope',
'headerservice',
'toastr',
function($scope, headerservice, toastr) {
$scope.showModal = false;
$scope.toggleModal = function() {
$scope.showModal = !$scope.showModal;
};
$scope.userSignin = function(){
$scope.userloginbtn = false;
if($scope.signin_form.$valid){ //Error on this line signin_form is undefine. using $valid for undefine
var record = {};
angular.extend(record, $scope.signinForm);
console.log(record);
}else {
$scope.signin_form.submitted = false;
$scope.userloginbtn = true;
}
};
} ]);
my directive.js file is
angular
.module('mint')
.directive(
'modal',
function() {
return {
template : '<div class="modal fade">'
+ '<div class="modal-dialog">'
+ '<div class="modal-content">'
+ '<div class="modal-header">'
+ '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>'
+ '<h4 class="modal-title"><span><i class="fa fa-user"></i> {{ title }}</span></h4>'
+ '</div>'
+ '<div class="modal-body" ng-transclude></div>'
+ '</div>' + '</div>' + '</div>',
restrict : 'E',
transclude : true,
replace : true,
scope : true,
link : function postLink(scope, element, attrs) {
scope.title = attrs.title;
scope.$watch(attrs.visible, function(value) {
if (value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = false;
});
});
}
};
});
My html file looks like
<!DOCTYPE html>
<html lang="en" ng-app="mintmygold">
<body>
<div class="container-fluid ban_bg"
ng-controller="headercontroller">
<div class="but_bg">
<button type="button" class="btn btn-default btn_sin" ng-click="toggleModal()">
<span><i class="fa fa-key"></i> Sign In</span>
</button>
</div>
<modal title="Login" visible="showModal">
<form role="form" name="signin_form" class="signup_form" novalidate
ng-model="signin_form">
<div class="form-group">
<p class="infoMsg" ng-model="signinform_info">Please fill in your login credentials:</p>
</div>
<div class="form-group">
<label for="email">Email address</label>
<input ng-model="signinForm.userEmail" name="userEmail" type="email" class="form-control" id="email" placeholder="Enter email" required />
<div
ng-show="signin_form.$submitted || signin_form.userEmail.$touched">
<span ng-show="signin_form.userEmail.$error.required">Enter your
email.</span> <span ng-show="signin_form.userEmail.$error.email">This
is not a valid email.</span>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input ng-model="signinForm.userPassword" name="userPassword" type="password" class="form-control" id="password" placeholder="Password" required />
<div
ng-show="signin_form.$submitted || signin_form.userPassword.$touched">
<span ng-show="signin_form.userPassword.$error.required">Enter your
password.</span>
</div>
</div>
<button ng-disabled="signin_form.$invalid || !userloginbtn" ng-model="signin" ng-click="userSignin()" type="submit" class="btn btn-primary">Submit</button>
</form>
</modal>
</div></body></html>
Now i can show the popup when click on sign in button. When i submit the form i couldn't get the values of email and password values from the pop up form in controller. what is my mistake of using the scope. Please any one help me.
With a quick overlook, it seems a silly mistake. Change your lines
From
angular.module('mint', ['ngAnimate', 'toastr']);
To
angular.module('mintmygold', ['ngAnimate', 'toastr']);
You are using scope: true which means your directive is creating a child scope and inheriting the properties from its parent.
Therefore any property you define in the directive scope does not exists on you controller scope.
Changing form name=signin_form
for form name=$parent.signin_form or scope: false should fix the problem
I didn't test this though. And it's not a good solution.
I would probably create a service that launches the pop-up and returns a promise that gets resolved/rejected accordingly.
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, modal) {
$scope.launch = function(){
modal.show().then(function(user){
console.log(user)
}, function(err){
console.log(err)
});
}
});
app.factory('modal', ["$document", "$compile", "$rootScope", "$templateCache", "$timeout", "$q",
function ($document, $compile, $rootScope, $templateCache, $timeout, $q) {
var $body = $document.find('body');
return {
show: function(){
var defer = $q.defer(),
child = $rootScope.$new();
child.user = {};
child.close = function(){
defer.reject('canceled');
tpl.remove();
}
child.submit = function(){
defer.resolve(child.user);
tpl.remove();
}
var tpl = angular.element($templateCache.get('modal.html'));
$compile(tpl)(child);
$body.append(tpl);
return defer.promise;
}
};
}]);
index.html
<script type="text/ng-template" id="modal.html">
<div class="modal in" style="position: static; display: block">
<div class="modal-dialog">
<form ng-submit="submit()" class="modal-content">
<div class="modal-header">
<button type="button" class="close" ng-click="close()" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
Email: <input ng-model="user.email"></input><br>
Password: <input ng-model="user.password"></input>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="close()">Close</button>
<button type="submit" class="btn btn-primary">Sign in</button>
</div>
</form>
</div>
</div>
</script>
<button type="button" ng-click="launch()" class="btn btn-primary">Show modal</button>
Plunker
This is just a proof of concept. I think is enough to get you started. I'd strongly recommend to checkout UI Bootstrap and the way the implement their modal

Resources