angularjs with angular-ui modal form - angularjs

Hi i am beginner for angularJS and i am showing angular-ui modal form when click on button and have to add new user but i am really confusing how to handle and how to do this scenario and i tried below code but its not working can some one help me better way to do this
My requirement i want to open modal form for adding new user and when i click save button i need to add that new user in my array
main.js
// create the module, pass in modules it depends on
var app = angular.module('myApp', ['ui.bootstrap']);
// $modal service is now available via the ui.bootstrap module we passed in to our module
app.controller('myController', ['$scope', '$uibModal', '$log',
function ($scope, $uibModal, $log) {
$scope.newUser = {};
$scope.info = "";
$scope.users = [
{ username: "rimon", fullName: "Md. Mamunur Rashid Rimon", email: "rimonmath#gmail.com" },
{ username: "shamim", fullName: "Md. Tamim Hossain", email: "shamim#gmail.com" },
{ username: "tamim", fullName: "Tamim Iqbal", email: "tamim#gmail.com" }
];
$scope.addUser = function () {
var modalInstance = $uibModal.open({
templateUrl: 'add_user.html',
controller: 'ModalInstanceCtrl',
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
}
$scope.saveUser = function () {
console.log("Saving...");
$scope.users.push($scope.newUser);
$scope.info = "New User Added Successfully!";
$scope.newUser = {};
};
$scope.selectUser = function (user) {
$scope.clickedUser = user;
};
$scope.deleteUser = function () {
console.log($scope.users.indexOf($scope.clickedUser));
$scope.users.splice($scope.users.indexOf($scope.clickedUser), 1);
$scope.info = "User Deleted Successfully!";
};
$scope.clearInfo = function () {
$scope.info = "";
};
}]);
angular.module('myApp').controller('ModalInstanceCtrl', function ($scope,$uibModalInstance) {
$scope.saveUser = function () {
alert("You clicked the ok button.");
$uibModalInstance.close();
};
$scope.close = function () {
alert("You clicked the cancel button.");
$uibModalInstance.dismiss('cancel');
};
});
Form.html
<div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">New User Registration</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="Username" ng-model="newUser.username">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="Email" ng-model="newUser.email">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Full Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="Full Name" ng-model="newUser.fullName">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="saveUser();">Save</button>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="close()">Close</button>
</div>
</div>

From what I see, your problem lies in your declaration of FormController.js please try to change this code :
app.controller('ModalInstanceCtrl', ['$scope','$modalInstance',function ($scope, $modalInstance) {
$scope.close = function () {
$modalInstance.dismiss('cancel');
};
$scope.saveUser = function(){
//SUBMIT FORM HERE
}
}]);
for this one :
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($uibModalInstance, data)
{
var pc = this;
pc.data = data;
pc.ok = function () {
//{...}
alert("You clicked the ok button.");
$uibModalInstance.close();
};
pc.cancel = function () {
//{...}
alert("You clicked the cancel button.");
$uibModalInstance.dismiss('cancel');
};
});
From your code I noticed that:
Your declaration of the modal controller misses the name of the main module app which sometimes is required.
you are using '$modalInstance' instead of $uibModalInstance
For further reference go here. Please try these changes and let me know if it works!

Related

how can update my form in modal in angular js?

hello i am creating mean application in which i want to update record.the record is in table format and when user click on edit button then a modal appears with its database values on input text box . I have not any problem in updating field but i stuck in updating video part. How can I do it??
html form (i use single form for creating and updating)
<div class="panel panel-default">
<div class="panel-heading">Add Videos</div>
<div class="panel-body">
<div style="margin:10px;">
<form name="addVideos" class="" method="post">
<div class="alert alert-success" ng-show="success" style="background-color:black;">
<strong>successfully updated!!</strong> Redirecting to all videos page.
</div>
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" ng-model="form.title" required name="title" placeholder="Enter Title">
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" ng-model="form.description" required name="description" rows="5" id="comment" placeholder="Enter Description"></textarea>
</div>
<div class="form-group">
<label>Author</label>
<input type="text" class="form-control" required ng-model="form.author" name="author" id="exampleInputPassword1" placeholder="Enter Author Name">
</div>
<div class="form-group">
<label>duration</label>
<input type="text" class="form-control" required ng-model="form.duration" name="duration" id="exampleInputPassword1" placeholder="Enter Author Name">
</div>
<!-- <div class="form-group">
<label>ispublic</label>
<input type="text" class="form-control" required ng-model="form.public" name="public" id="exampleInputPassword1" placeholder="Enter Author Name">
</div> -->
<div class="form-group">
<label for="sel1">ispublic:</label>
<select class="form-control" ng-model="form.public" >
<option ng-selected="test==false" value="0">0</option>
<option ng-selected="test==true" value="1">1</option>
</select>
</div>
<div class="row">
<div class="col-md-2" style="margin-top: 19px;" >
<!-- <!ng-hide="display" !> -->
<input type="file" accept="video/*" file-model="myFile" required/>
</div>
<div class="col-md-8" style="margin-left:29px;">
<button ng-click="add == true ? uploadFile(form) : updateVideo()" class="btn btn-danger" ng-disabled="addVideos.$invalid" style="margin:10px;">Submit</button>
</div>
</div>
<progress value="{{progressBar}}" max="100" ng-show="view">
</progress>
<div class="progress" ng-show="view" style="width:40%;">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="{{progressBar}}" aria-valuemin="0" aria-valuemax="100" style="width:{{progressBar}}%">
{{progressBar}}% Complete (success)
</div>
</div>
</form>
</div>
</div>
</div>
my controller
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxx.mp4'.replace(/[xy]/g, function(c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
};
var localstorageApp = angular.module('BlurAdmin.pages.videos.allVideos');
localstorageApp.controller('TbleCtrl',['$rootScope','$scope', '$filter', 'editableOptions', 'editableThemes', '$window', '$http',
'$uibModal', 'baProgressModal','localStorageService','$state','$rootScope',
function ($rootScope,$scope, $filter, editableOptions, editableThemes, $window, $http, $uibModal,
baProgressModal,localStorageService,$state,$rootScope) {
var token = localStorageService.get('TOKEN')
if(token == null){
$window.location.href = '/index.html';
}
token = token.substring(1, token.length - 1);
$http.get("/api/loggedin/"+token).then(function(response) {
console.log("response"+JSON.stringify(response.data.error))
if(response.data.error == true){
localStorageService.remove('TOKEN')
$window.location.href = '/index.html';
}
});
$scope.users = [];
$scope.display=true;
// $scope.form = [];
//$scope.bool = null;
$scope.id = 0;
$scope.redirect = function () {
$window.location.href = "#/videos/addVideos";
}
$http.get("/api/all-videos").then(function(response) {
$scope.users = response.data.data;
console.log(response.data.data);
});
$scope.open = function(e,id,page, size, addOrEdit) {
$scope.updateVideo() = function(){
alert('working');
}
// $scope.bool = bool
$scope.id = id
$scope.display=true;
var modalInstance = $uibModal.open({
// animation: $ctrl.animationsEnabled,
// ariaLabelledBy: 'modal-title',
// ariaDescribedBy: 'modal-body',
templateUrl: page,
controller: 'ModalInstanceCtrl',
controllerAs: '$scope',
size: size,
// appendTo: parentElem,
resolve: {
users: function () {
return $scope.users;
},
id: function () {
return $scope.id;
}
}
});
modalInstance.result.then(function (selectedItem) {
// console.log("selectedItem"+JSON.stringify(selectedItem.data));
$scope.users = selectedItem;
// $scope.users.push(selectedItem.data)
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.removeVideo = function(id, $index) {
var m = parseInt(id);
if ($window.confirm("Are you sure you want to delete?") == true) {
$http.post("/api/delete-video/" + m).then(function(response) {
$scope.users.splice( $index, 1 );
});
// $window.location.reload()
} else {
}
}
$scope.openProgressDialog = baProgressModal.open;
// editableOptions.theme = 'bs3';
// editableThemes['bs3'].submitTpl = '<button type="submit" class="btn btn-primary btn-with-icon"><i class="ion-checkmark-round"></i></button>';
// editableThemes['bs3'].cancelTpl = '<button type="button" ng-click="$form.$cancel()" class="btn btn-default btn-with-icon"><i class="ion-close-round"></i></button>';
}
])
var qwe='';
angular.module('BlurAdmin.pages.users').directive('fileModel', ['$parse', function($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].files[0]);
qwe= element[0].files[0];
console.log(element[0].files[0].name);
});
});
}
};
}]).service('hexafy', ['$http', '$window','$timeout', function($http, $window,$timeout) {
this.myFunc = function (x) {
return x.toString(16);
}
// GET ALL INFORMATION IN VIDEOS
this.getAll = function(t,x){
console.log(x);
$http.get("/api/get-video/"+x).then(function(response) {
console.log(response);
// console.log(response.data.data);
console.log(response.data.response.data);
t.form = response.data.response.data;
// $scope.form.public = response.data.response.data.ispublic;
t.test = response.data.response.data.ispublic;
// console.log($scope.form.level);
// $scope.form.level = $scope.levels[response.data.response.data.level - 1];
// console.log($scope.form.level);
});
}
this.display = function(p){
console.log(p);
console.log(qwe);
}
this.updateVideo = function(){
console.log(qwe);
alert('working');
}
}]).controller('ModalInstanceCtrl', ['$scope', '$uibModalInstance', '$http', 'id', '$timeout','hexafy' ,function ($scope, $uibModalInstance,$http,id,$timeout,hexafy) {
$scope.form = {};
$scope.test = '';
// $scope.b = bool;
console.log($scope.b);
$scope.display=true;
console.log(hexafy.myFunc(187));
hexafy.getAll($scope,id);
console.log("id value "+id)
var file = $scope.myFile;
console.log(file);
}])
How could i detect file in modal??

Get data from controller in Angular js

I tried to create a small service for adding and getting. I have successfully added details when I click register(form details are added)in one controller. Now I want that form details in another controller, but I'm not getting it. I'm able to get that details in that get function and able to print in console but I cannot pass them to html
Here is my HTML:
<div id="inputArea" style="border: 1px solid blue;width: 800px;height: 45px;margin: auto;" ng-controller="MyFormCtrl">
<form name="myForm" ng-submit="register()">
<input class="inputfield" type="text" style="margin-left: 13px;" placeholder="enter first name" ng-model="user.fname">
<input class="inputfield" type="text" style="margin-left: 13px;" placeholder="enter last name" ng-model="user.lname">
<input class="inputfield" type="text" style="margin-left: 10px;" placeholder="enter designation" ng-model="user.designation">
<input class="inputfield" type="text" style="margin-left: 10px;" placeholder="enter company" ng-model="user.company">
<input type="submit" style="float:right;" value="Register"> </form>
</div>
<div id="box" style="position: relative;top:200px;margin: auto;border:1px solid red;width:180px;height:90px;" ng-controller="DetailsConroller">
<input type="button" ng-click="getDetails()" value="get">
<!-- <input type="submit" style="" value="get">-->
<ul>
<li ng-repeat="x in employees"> {{ x.fname }} </li>
</ul>
</div>
my js:
var app = angular.module('myApp', []);
--->service for adding and get
app.service('employeeService', ['$rootScope', function ($rootScope) {
var employeeList = [];
return {
employeeList: []
, // var employeeList = [],
add: function (item) {
employeeList.push(item);
console.log('employeeList', employeeList);
}
, get: function () {
// console.log('in to get employeeList',employeeList);
return employeeList
}
};
}])
---->> COntroller to Add:
app.controller('MyFormCtrl', ['$scope', 'employeeService', function ($scope, employeeService) {
$scope.user = {
fname: ''
, lname: ''
, designation: ''
, company: ''
};
$scope.register = function () {
console.log('User clicked register', this.user);
employeeService.add(this.user);
//employeeService.updateUserData().set($rootScope.user);
};
}]);
--->>second controller to get:
app.controller('DetailsConroller', ['$scope', 'employeeService', function ($scope, employeeService) {
var employees = [];
$scope.getDetails = function () {
// console.log('User clicked register', this.user);
employees = employeeService.get();
console.log('User in to get', employees[0].fname);
return employees;
};
}]);
what am I doing wrong here?
You need to have a $scope variable,
Change your Controller like this,
app.controller('DetailsConroller', ['$scope', 'employeeService', function ($scope, employeeService) {
$scope.employees = [];
// console.log('User clicked register', this.user);
$scope.employees = employeeService.get();
console.log('User in to get', employees[0].fname);
}]);

ng-model data not getting when saving the data

here save the ng-model is newattendance saving to database. "newattendance._id" is not taken as a ng-model.how to make it "newattendance._id" is ng-model
<select class="form-control" ng-options="item.empcode as item.empcode for item in totemplist" ng-model="item.empcode">
</select>
<input type="text" ng-repeat="newattendance in totemplist" ng-model="newattendance._id" ng-show="item.empcode ==newattendance.empcode" style="width:200px;" ><br>
<input placeholder="Enter Attendacne Date" ng-model="newattendance.doa">
<button class="btn btn-primary" ng-click="checkOut()">checkOut</button>
Controller
EmpMasterController.controller("AttendanceController", ['$scope', 'AttendanceFactory',"EmpAddService", function($scope, AttendanceFactory,EmpAddService){
$scope.newattendance={};
$scope.totemplist=EmpAddService.getAllEmpAddItems();
console.log($scope.totemplist);
$scope.checkIn = function(){
AttendanceFactory.addAttendance($scope.newattendance);
$scope.newattendance = {}
}
$scope.getAllAttendance = function(){
console.log("$$$$$"+$scope.newattendance._id)
$scope.attendancedetails =AttendanceFactory.getAllAttendance($scope.newattendance._id);
}
}])
Factory
EmpFactModule.factory("AttendanceFactory", function($resource, RES_URL){
var attendanceResource = $resource(RES_URL+"attandence/:id/:attid",
{"id": "#id", "attid": "#attid"}, {update: {method: "PUT"}})
var attendanceDetails;
return {
addAttendance: function(newattendance){
console.log("..1.. " + newattendance._id)
attendanceResource.save({"id":newattendance._id}, newattendance, function(data){
console.log("Add Success ")
}, function(data, status){
console.log("Add Failed*****");
})
},
getAllAttendance: function(_id){
console.log("..#.. " + _id)
attendanceDetails = attendanceResource.query({"id": _id});
return attendanceDetails;
},
}
})
please help me how make it as ng-model and how to save this...
I've create a JSFiddle for you which hopefully will help you understand the 2 way binding in angular.
you dont need to pass the newattendance object to the check-out function, it is already saved on the scope.
HTML:
<div ng-app="app">
<div ng-controller="formValidation">
<div>
<div>
<span>User Name</span>
<input type="text" placeholder="John" ng-model="newattendance._id">
<span>
<button ng-click="submit()">
check out
</button>
</span>
</div>
</div>
<pre>{{newattendance._id}}</pre>
</div>
</div>
JS:
var app = angular.module('app', []);
app.controller('formValidation', function($scope) {
$scope.submit=function(){
var formPost = {
"Username":$scope.newattendance._id
};
console.log(formPost);
}
});

Angularjs scope not working

I am using basic angular.js concept to show and hide a div. For some reasons I am unable to make it work.
While Uploading a file I am showing a div 'myFormSpinner' on the basis of registerStart value. I am creating a phone gap app.
Could someone please help me in finding the issue. Apart from showing/hiding div everything works fine. Below is the code snippet:
<div class="row" ng-controller="RegisterCtrl">
<div id="myFormSpinner" ng-show="registerStart">
<img src="img/ajax-loader.gif">
</div>
<div class="col-md-8">
<form class="ng-pristine ng-invalid ng-invalid-required" style="margin-top:5%;">
<div class="col-md-6">
<input class="form-control " type="text" ng-model="registerData.Email" id="Email" name="Email" required placeholder="Email">
</div>
<div class="col-md-offset-1 col-md-10 ">
<input type="submit" ng-click="register()" value="Register" class="btn btn-default btn-primary">
</div>
</form>
</div>
event.controller('RegisterCtrl', ['$scope', '$state', '$q', '$http', 'eventService', 'authService', '$stateParams', '$rootScope', 'tokenService', 'imageService', 'spinnerService', 'appBackgroundService',
function ($scope, $state, $q, $http, eventService, authService, $stateParams, $rootScope, tokenService, imageService, spinnerService, appBackgroundService) {
var userNumber = 0;
$scope.mediaUploadStart = false;
$scope.eventId = $state.params.id;
$scope.register = function () {
$scope.registerStart = true;
console.log('scope.Pic=' + $scope.pic);
if ($scope.registerData.Email) {
spinnerService.show('myFormSpinner');
$scope.mediaUploadStart = true;
var paramOptions = {
eventId: $state.params.id,
email: $scope.registerData.Email,
fb: {},
number: userNumber,
provider: "Form"
};
uploadPicAndData(paramOptions).then(function (result) {
var data = JSON.parse(result);
$scope.registerStart = false;
appBackgroundService.disableBackgroundMode();
},
function (error) {
spinnerService.hide('myFormSpinner');
$scope.registerStart = false;
appBackgroundService.disableBackgroundMode();
});
$scope.mediaUploadStart = false;
spinnerService.hide('myFormSpinner');
}
};
}])
You are setting the $scope element in an async mode.
the digest cycle is not able to determine that a change has been made to the scope element in an async mode.
You should use $apply to activate the digest cycle.
$scope.$apply(function () { $scope.registerStart = false; });
Read more about $apply here: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Bind values to UI Bootstrap Modal

I have a table with a view button, when view is clicked modal display but now I want to display certain data on the modal. I am using .html pages.
I am not sure what am I missing here
html
<td>
<span>
<input class="btn btn-sm btn-dark" data-ng-click="launch('create',client)" type="button" value="view" />
</span>
</td>
This will luanch the modal
Modal
<div class="modal fade in" ng-controller="dialogServiceTest">
<div class="modal ng-scope">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">
<span class="glyphicon glyphicon-star"></span> Client Details
</h4>
</div><div class="modal-body">
<ng-form name="nameDialog" novalidate="" role="form" class="ng-pristine ng-invalid ng-invalid-required">
<div class="form-group input-group-lg" ng-class="{true: 'has-error'}[nameDialog.username.$dirty && nameDialog.username.$invalid]">
<label class="control-label" for="username">Name:</label>
<input type="text" name="username" id="username" ng-model="client.ClientName" ng-keyup="hitEnter($event)" required="">
<span class="help-block">Enter your full name, first & last.</span>
</div>
<div>{{client.ClientName}}</div>
</ng-form>
</div><div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="cancel()">Cancel</button>
<button type="button" class="btn btn-primary" ng-click="save()" ng-disabled="(nameDialog.$dirty && nameDialog.$invalid) || nameDialog.$pristine" disabled="disabled">Save</button>
</div>
</div>
</div>
</div>
Angular
angular.module('modalTest', ['ngRoute','ui.bootstrap', 'dialogs'])
.controller('dialogServiceTest', function ($scope,$http, $rootScope, $timeout, $dialogs) {
$scope.clients = []; //Array of client objetcs
$scope.client = {}; //Single client object
$scope.launch = function (which,client) {
var dlg = null;
alert(client.ClientName);
dlg = $dialogs.create('/templates/Modal.html', 'whatsYourNameCtrl', {}, { key: false, back: 'static' });
dlg.result.then(function () {
$scope.client.ClientName = client.ClientName;
});
})
.run(['$templateCache', function ($templateCache) {
$templateCache.put('/templates/Modal.html');
}]);
here is some of my code
$scope.showScreenSizePicker = function(){
$scope.actionmsg = "";
var modalWindow = $modal.open({
templateUrl: '{{url()}}/modals/modalScreenSizePicker',
controller: 'modalScreenSizePickerController',
resolve: {
titletext: function() {return "Screen Sizes: ";},
oktext: function() {return "Close";},
canceltext: function() {return "Cancel";},
labeltext: function() {return "";},
}});
modalWindow.result.then(function(returnParams) {
$scope.setViewSize(returnParams[0], returnParams[1]);
});
}
you can see i am passing variables into modal using resolve. If you want to pass values back from the modal you can grab the variable returnParms (array)
and here is my controller code:
angular.module('myWebApp').controller('modalScreenSizePickerController', function($scope, $modalInstance, titletext, labeltext, oktext, canceltext) {
$scope.titletext = titletext;
$scope.labeltext = labeltext;
$scope.oktext = oktext;
$scope.canceltext = canceltext;
$scope.customHeight = 800;
$scope.customWidth = 600;
$scope.selectCustomSize = function(width, height){
if (width < 100){ width = 100; }
if (height < 100){ height = 100; }
$scope.selectItem(width, height);
}
$scope.selectItem = function(width, height) {
var returnParams = [width, height];
$modalInstance.close(returnParams);
};
$scope.cancel = function() {
$modalInstance.dismiss();
};
});
hope my sample helps
I think what you are looking for is the resolve property you can use with the $modal service. I am not exactly sure which version of UI Bootstrap you are using, but the latest one works as follows:
var myModal = $modal.open({
templateUrl: '/some/view.html',
controller: 'SomeModalCtrl',
resolve: {
myInjectedObject: function() { return someObject; }
});
myModal.result.then(function(){
// closed
}, function(){
// dismissed
});
Then you can use the injected resolved value inside the modals controller:
app.controller('SomeModalCtrl', function ($scope, $modalInstance, myInjectedObject) {
// use myInjectedObject however you like, eg:
$scope.data = myInjectedObject;
});
You can acces the client in modal by using "$scope.$parent.client" - "$parent" give you $scope from witch the modal was open with all data.

Resources