Image uploading/cropping functionality is not working in tabset in angularjs - angularjs

I am new to angularjs.
I want to implement https://angular-file-upload.appspot.com/ image upload functionality in tabs. When I put html elements which are required for image upload inside
<tabset><tab></tab></tabset> it doesn't work, but when I put it outside tabset it worked fine, but I want it inside <tabset><tab></tab></tabset>.
I am getting this error when I put html code inside <tabset></tabset>
Error: document.getElementById(...) is null
handleDynamicEditingOfScriptsAndHtml#http://localhost/angularAdmin/js/controllers/userForm.js:190:34
#http://localhost/angularAdmin/js/controllers/userForm.js:189:1
invoke#http://localhost/angularAdmin/vendor/angular/angular.js:4118:14
$ControllerProvider/this.$get</</<#http://localhost/angularAdmin/vendor/angular/angular.js:8356:11
nodeLinkFn/<#http://localhost/angularAdmin/vendor/angular/angular.js:7608:13
forEach#http://localhost/angularAdmin/vendor/angular/angular.js:347:11
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7607:11
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3768:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3768:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/</<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3762:11
$RootScopeProvider/this.$get</Scope.prototype.$broadcast#http://localhost/angularAdmin/vendor/angular/angular.js:14518:15
transitionTo/$state.transition<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3169:11
processQueue#http://localhost/angularAdmin/vendor/angular/angular.js:12984:27
scheduleProcessQueue/<#http://localhost/angularAdmin/vendor/angular/angular.js:13000:27
$RootScopeProvider/this.$get</Scope.prototype.$eval#http://localhost/angularAdmin/vendor/angular/angular.js:14200:16
$RootScopeProvider/this.$get</Scope.prototype.$digest#http://localhost/angularAdmin/vendor/angular/angular.js:14016:15
$RootScopeProvider/this.$get</Scope.prototype.$evalAsync/<#http://localhost/angularAdmin/vendor/angular/angular.js:14238:15
completeOutstandingRequest#http://localhost/angularAdmin/vendor/angular/angular.js:4842:7
Browser/self.defer/timeoutId<#http://localhost/angularAdmin/vendor/angular/angular.js:5215:7
<div ui-view="" class="fade-in ng-scope">
[1]: https://angular-file-upload.appspot.com/
app.js
'use strict';
angular.module('app', [
'ngFileUpload',
'toaster',
'LocalStorageModule',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'ngTouch',
'ngStorage',
'ui.router',
'ui.bootstrap',
'ui.load',
'ui.jq',
'ui.validate',
'oc.lazyLoad',
'pascalprecht.translate'
]);
Controller
'use strict';
/* Controllers */
var version = '3.0.6';
// Form controller
app.controller('FormProfileCtrl', ['$scope', '$http', '$timeout', '$compile', '$upload', function ($scope, $http, $timeout, $compile, $upload) {
$scope.usingFlash = FileAPI && FileAPI.upload != null;
$scope.fileReaderSupported = window.FileReader != null && (window.FileAPI == null || FileAPI.html5 != false);
$scope.changeAngularVersion = function () {
window.location.hash = $scope.angularVersion;
window.location.reload(true);
};
$scope.angularVersion = window.location.hash.length > 1 ? (window.location.hash.indexOf('/') === 1 ?
window.location.hash.substring(2) : window.location.hash.substring(1)) : '1.2.20';
$scope.$watch('files', function (files) {
console.log(files);
$scope.formUpload = false;
if (files != null) {
for (var i = 0; i < files.length; i++) {
$scope.errorMsg = null;
(function (file) {
generateThumbAndUpload(file);
})(files[i]);
}
}
});
$scope.uploadPic = function (files) {
$scope.formUpload = true;
if (files != null) {
generateThumbAndUpload(files[0])
}
}
function generateThumbAndUpload(file) {
$scope.errorMsg = null;
$scope.generateThumb(file);
if ($scope.howToSend == 1) {
uploadUsing$upload(file);
} else if ($scope.howToSend == 2) {
uploadUsing$http(file);
} else {
uploadS3(file);
}
}
$scope.generateThumb = function (file) {
if (file != null) {
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function () {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (e) {
$timeout(function () {
file.dataUrl = e.target.result;
});
}
});
}
}
}
function uploadUsing$upload(file) {
file.upload = $upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'my-header': 'my-header-value'
},
fields: {username: $scope.username},
file: file,
fileFormDataName: 'myFile',
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
file.upload.xhr(function (xhr) {
// xhr.upload.addEventListener('abort', function(){console.log('abort complete')}, false);
});
}
function uploadUsing$http(file) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
$timeout(function () {
file.upload = $upload.http({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'Content-Type': file.type
},
data: e.target.result
});
file.upload.then(function (response) {
file.result = response.data;
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}, 5000);
}
fileReader.readAsArrayBuffer(file);
}
function uploadS3(file) {
file.upload = $upload
.upload({
url: $scope.s3url,
method: 'POST',
fields: {
key: file.name,
AWSAccessKeyId: $scope.AWSAccessKeyId,
acl: $scope.acl,
policy: $scope.policy,
signature: $scope.signature,
"Content-Type": file.type === null || file.type === '' ? 'application/octet-stream' : file.type,
filename: file.name
},
file: file,
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
storeS3UploadConfigInLocalStore();
}
$scope.generateSignature = function () {
$http.post('/s3sign?aws-secret-key=' + encodeURIComponent($scope.AWSSecretKey), $scope.jsonPolicy).
success(function (data) {
$scope.policy = data.policy;
$scope.signature = data.signature;
});
}
if (localStorage) {
$scope.s3url = localStorage.getItem("s3url");
$scope.AWSAccessKeyId = localStorage.getItem("AWSAccessKeyId");
$scope.acl = localStorage.getItem("acl");
$scope.success_action_redirect = localStorage.getItem("success_action_redirect");
$scope.policy = localStorage.getItem("policy");
$scope.signature = localStorage.getItem("signature");
}
$scope.success_action_redirect = $scope.success_action_redirect || window.location.protocol + "//" + window.location.host;
$scope.jsonPolicy = $scope.jsonPolicy || '{\n "expiration": "2020-01-01T00:00:00Z",\n "conditions": [\n {"bucket": "angular-file-upload"},\n ["starts-with", "$key", ""],\n {"acl": "private"},\n ["starts-with", "$Content-Type", ""],\n ["starts-with", "$filename", ""],\n ["content-length-range", 0, 524288000]\n ]\n}';
$scope.acl = $scope.acl || 'private';
function storeS3UploadConfigInLocalStore() {
if ($scope.howToSend == 3 && localStorage) {
localStorage.setItem("s3url", $scope.s3url);
localStorage.setItem("AWSAccessKeyId", $scope.AWSAccessKeyId);
localStorage.setItem("acl", $scope.acl);
localStorage.setItem("success_action_redirect", $scope.success_action_redirect);
localStorage.setItem("policy", $scope.policy);
localStorage.setItem("signature", $scope.signature);
}
}
(function handleDynamicEditingOfScriptsAndHtml($scope, $http) {
$scope.defaultHtml = document.getElementById('editArea').innerHTML.replace(/\t\t\t\t/g, '');
$scope.editHtml = (localStorage && localStorage.getItem("editHtml" + version)) || $scope.defaultHtml;
function htmlEdit(update) {
document.getElementById("editArea").innerHTML = $scope.editHtml;
$compile(document.getElementById("editArea"))($scope);
$scope.editHtml && localStorage && localStorage.setItem("editHtml" + version, $scope.editHtml);
if ($scope.editHtml != $scope.htmlEditor.getValue())
$scope.htmlEditor.setValue($scope.editHtml);
}
$scope.$watch("editHtml", htmlEdit);
$scope.htmlEditor = CodeMirror(document.getElementById('htmlEdit'), {
lineNumbers: true, indentUnit: 4,
mode: "htmlmixed"
});
$scope.htmlEditor.on('change', function () {
if ($scope.editHtml != $scope.htmlEditor.getValue()) {
$scope.editHtml = $scope.htmlEditor.getValue();
htmlEdit();
}
});
})($scope, $http);
$scope.confirm = function () {
return confirm('Are you sure? Your local changes will be lost.');
}
$scope.getReqParams = function () {
return $scope.generateErrorOnServer ? "?errorCode=" + $scope.serverErrorCode +
"&errorMessage=" + $scope.serverErrorMsg : "";
}
angular.element(window).bind("dragover", function (e) {
e.preventDefault();
});
angular.element(window).bind("drop", function (e) {
e.preventDefault();
});
}])
;
View
<div class="bg-light lter b-b wrapper-md">
<h1 class="m-n font-thin h3">Edit User</h1>
</div>
<div class="wrapper-md">
<!-- breadcrumb -->
<div>
<ul class="breadcrumb bg-white b-a">
<li><a ui-sref="app.dashboard"><i class="fa fa-home"></i> Dashboard</a></li>
<li class="active">Edit User</li>
</ul>
</div>
<!-- / breadcrumb -->
<div class="col-lg-12">
<div class="wrapper-md" ng-controller="FormProfileCtrl">
<form name="userForm" class="form-validation">
<tabset justified="true" class="tab-container">
<tab heading="Personal Information">
<div class="panel-body">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" ng-model="user.vName" >
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" ng-model="user.vEmail">
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" ng-model="user.vPhone" >
</div>
<div class="form-group">
<label>Address</label>
<textarea class="form-control" ng-model="user.vAddress" ></textarea>
</div>
<div class="form-group pull-in clearfix">
<div class="col-sm-6">
<label>Enter password</label>
<input type="password" class="form-control" name="vPassword" ng-model="vPassword" >
</div>
<div class="col-sm-6">
<label>Confirm password</label>
<input type="password" class="form-control" name="confirm_password" required ng-model="confirm_password" ui-validate=" '$value==password' " ui-validate-watch=" 'password' ">
<span ng-show='form.confirm_password.$error.validator'>Passwords do not match!</span>
</div>
</div>
</div>
</tab>
<tab heading="Company Information">
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control" ng-model="user.vCompanyName" >
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" ng-model="user.vCompanyPhone" >
</div>
<div class="form-group">
<label>Designation</label>
<input type="text" class="form-control" ng-model="user.vDesignation" >
</div>
<div class="form-group">
<label>Address</label>
<textarea class="form-control" ng-model="user.vCompanyAddress" ></textarea>
</div>
</tab>
</tabset>
<!-- I want -->
<div class="upload-div">
<div class="upload-buttons">
<div id="editArea">
<fieldset><legend>Upload right away</legend>
<div ng-file-drop ng-file-select ng-model="files" ng-model-rejected="rejFiles"
drag-over-class="{accept:'dragover', reject:'dragover-err', delay:100}" class="drop-box"
ng-multiple="true" allow-dir="true" ng-accept="'image/*,application/pdf'">
Drop Images or PDFs<div>or click to select</div>
</div>
<div ng-no-file-drop class="drop-box">File Farg&Drop not supported on your browser</div>
</fieldset>
<br/>
</div>
</div>
<ul ng-show="rejFiles.length > 0" class="response">
<li class="sel-file" ng-repeat="f in rejFiles">
Rejected file: {{f.name}} - size: {{f.size}}B - type: {{f.type}}
</li>
</ul>
<ul ng-show="files.length > 0" class="response">
<li class="sel-file" ng-repeat="f in files">
<img ng-show="f.dataUrl" ng-src="{{f.dataUrl}}" class="thumb">
<span class="progress" ng-show="f.progress >= 0">
<div style="width:{{f.progress}}%">{{f.progress}}%</div>
</span>
<button class="button" ng-click="f.upload.abort();
f.upload.aborted = true"
ng-show="f.upload != null && f.progress < 100 && !f.upload.aborted">Abort</button>
{{f.name}} - size: {{f.size}}B - type: {{f.type}}
<a ng-show="f.result" href="javascript:void(0)" ng-click="f.showDetail = !f.showDetail">details</a>
<div ng-show="f.showDetail">
<br/>
<div data-ng-show="f.result.result == null">{{f.result}}</div>
<ul>
<li ng-repeat="item in f.result.result">
<div data-ng-show="item.name">file name: {{item.name}}</div>
<div data-ng-show="item.fieldName">name: {{item.fieldName}}</div>
<div data-ng-show="item.size">size on the serve: {{item.size}}</div>
<div data-ng-show="item.value">value: {{item.value}}</div>
</li>
</ul>
<div data-ng-show="f.result.requestHeaders" class="reqh">request headers: {{f.result.requestHeaders}}</div>
</div>
</li>
</ul>
<br/>
<div class="err" ng-show="errorMsg != null">{{errorMsg}}</div>
</div>
<input type="hidden" class="form-control" ng-model="user.iUserID">
<input type="submit" class="btn btn-success" ng-click="postForm(user)">
</form>
</div>
</div>

I had a similar problem with ng-file-upload and tabset. Here is how I solved it.
In my controller, I created a new object:
$scope.tab_data = {}
and then changed the watch to
$scope.$watch 'tab_data.files', ->
$scope.upload $scope.tab_data.files
Lastly, I updated the ng-model in my html tag.
<div ngf-drop ngf-select ng-model="tab_data.files" class="drop-box" ngf-drag-over-class="dragover" ngf-multiple="true" ngf-allow-dir="true" ngf-accept="'.jpg,.png,.pdf'" class="drop-box">
<div ngf-drop-available >Drop Images here</div>
<div ngf-no-file-drop>File Drag/Drop is not supported for this browser</div>
<div>click to select</div>
</div>
Of course my solution is in coffeescript...sorry if that is an issue but it should be easy for you to convert back to js.

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??

Angular ui-calendar auto refresh on form submission

i am using angular ui-calendar for displaying a series of leaves.The data for this is fed from the REST services.I can add a leave to the database also.The problem is that when i add a leave detail to the database it does not automatically reflect in the calendar.If i refresh the page the data will be reflected. Basically what I want to do is when I submit the form (closing the modal) the data to be displayed in the calendar. Thank you in advance.Following is my code
My controller
app.factory('calendarSer', ['$http', '$rootScope', 'uiCalendarConfig', function($http, $rootScope, uiCalendarConfig) {
return {
displayCalendar: function($scope) {
$http.get("rest/leave/holidayList", {}).success(function(data, status, headers, config) {
$scope.holidayList = data;
$calendar = $('[ui-calendar]');
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$scope.changeView = function(view) {
$calendar.fullCalendar('changeView', view);
};
var m = null;
if ($scope.selectable == "Yes") {
m = true;
} else {
m = false;
}
/* config object */
$scope.uiConfig = {
calendar: {
lang: 'da',
height: 400,
editable: true,
selectable: m,
header: {
left: 'month basicWeek basicDay',
center: 'title',
right: 'today prev,next'
},
eventClick: function(date, jsEvent, view) {
$scope.alertMessage = (date.title + ' was clicked ');
alert("clicked" + date.title);
},
select: function(start, end, allDay) {
var obj = {};
obj.startDate = start.toDate();
obj.endDate = moment(end - 1 * 24 * 3600 * 1000).format('YYYY-MM-DD');
$rootScope.selectionDate = obj;
$("#modal1").openModal();
// calendar.fullCalendar('unselect');
},
dayRender: function(date, cell) {
var today = new Date();
today = moment(today).toDate();
var end = new Date();
end = moment(end).toDate();
end.setDate(today.getDate() + 7);
date = moment(date).toDate();
angular.forEach($scope.holidayList, function(value) {
if (((moment(value.holiday_date).format("YYYY-MM-DD")) == moment(date).format("YYYY-MM-DD"))) {
cell.css("background-color", "#2bbbad");
//$('.date').text('Today');
cell.prepend("<span style=\"max-width:200px;word-wrap:break-word;margin-top:10px;\">" + value.description + "</span>");
cell.prepend("<br>")
}
});
},
eventRender: $scope.eventRender,
}
};
console.log($scope.holidayList);
}).error(function(data, status, headers, config) {
alert("error from holidaylist");
});
$scope.events = [];
$scope.eventSources = [$scope.events];
$http.get($scope.url, {
cache: true,
params: {}
}).then(function(data) {
console.log(data);
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function(value) {
console.log(value.title);
if (value.approvalStatus == "Approved") {
var k = '#114727';
} else {
k = '#b20000'
}
$scope.events.push({
title: value.signum,
description: value.signum,
start: value.startDate,
end: value.endDate,
allDay: value.isHalfDay,
stick: true,
status: value.approvalStatus,
backgroundColor: k
});
});
});
}
}
}]);
g-include
<div id="controllerid">
<div class="row" >
<div class="col s10 m10 l10">
<div id="calendar" ui-calendar="uiConfig.calendar" ng-model="eventSources" calendar="myCalendar"></div>
</div>
</div>
<!-- Modal Structure -->
<div id="modal1" class="modal" ng-controller="MyAddController">
<div class="modal-content">
<h4>Apply Leave</h4>
<div class="row">
<form class="col s12" id="form1">
<div class="row modal-form-row">
<div class="input-field col s6">
<input id="num" type="text" class="validate" ng-model="test.num"> <label for="num">num</label>
</div>
<div class="input-field col s6">
<input id="ename" type="text" class="validate" ng-model="test.title"> <label for="ename">Employee Name</label>
</div>
</div>
<div class="row">
<form class="col s12">
<div class="row modal-form-row">
<div class="input-field col s5">
<input id="startDate" type="text" class="validate" value="{{selectionDate.startDate | date}}" readonly >
</div>
<div class="input-field col s5">
<input id="endDate" type="text" class="validate" value="{{selectionDate.endDate | date}}" readonly>
</div>
<div class="input-field col s1">
<p>
<input type="checkbox" id="test6" ng-model="test.isHalfDay" /> <label for="test6">Half Day</label>
</p>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="description" type="text" class="validate" ng-model="test.description"> <label for="description">Description</label>
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button class="btn waves-effect waves-light" type="submit" ng-click="add()" name="action"> Submit <i class="material-icons right">send</i>
</button>
</div>
</div>
and my add controller
app.controller("MyAddController", function($scope, $http,$rootScope,calendarSer) {
$scope.test = {};
$scope.add = function() {
$("#modal1").closeModal();
$scope.test1=$rootScope.selectionDate;
var jsonData = JSON.stringify($.extend({}, $scope.test, $scope.test1));
console.log(""+jsonData);
$http({
url: "rest/leave/create",
method: "POST",
data: jsonData,
headers: {'Content-Type': 'application/json'}
}).success(function(data, status, headers, config) {
if (data) {
console.log("Entered in the add controller");
$scope.data = data;
$scope.url="rest/leave/list";
$scope.selectable="Yes";
calendarSer.displayCalendar($scope);
$("#popupmodal").openModal();
console.log("Exited in the add controller");
}
}).error(function(data, status, headers, config) {
alert("error from create leave");
})
}
});
ANy help would be appreciated
In your "success" function after you run the "create" function, you can simply add the event to fullCalendar using the same data, via the built-in "renderEvent" function.
Something like this (I don't know Angular, so you may need to adjust this slightly to get your calendar element into context, but hopefully you understand the idea). I am also assuming that jsonData contains all the relevant event data which we can use for this:
.success(function(data, status, headers, config) {
if (data) {
console.log("Entered in the add controller");
$scope.data = data;
//add the event to the calendar UI without refreshing the events
$('[ui-calendar]').fullCalendar("renderEvent",
{
start: jsonData.startDate,
end: jsonData.endDate,
title: jsonData.title
},
true //make it stick even when the view changes
);
$scope.url="rest/leave/list";
$scope.selectable="Yes";
calendarSer.displayCalendar($scope);
$("#popupmodal").openModal();
console.log("Exited in the add controller");
}
You may need to add more fields, or you may need to get momentJS to parse the values in startDate / endDate, depending exactly what those fields output.
The "renderEvent" method can be found in the fullCalendar documentation here: https://fullcalendar.io/docs/event_rendering/renderEvent/

Angular JS: update controller when data change in second controller

what i m doing:
simple html file shows first page , in this page i have one title and button, initially i set $scope.index = 0. so, we set first position of array. when we click on next button it finds firstCtrl and first.html page. in this controller i update $scope.index by 1. so, my question is when i update $scope.index of myCtrl then $scope.index is changed on another controller i wants to change myCtrl. is it possible ? if it is then help me.
index.html:
<body ng-controller="myCtrl">
<div id="navbar">
<div class="setToggle">
<input id="slide-sidebar" type="checkbox" role="button" />
<label for="slide-sidebar"><span class="glyphicon glyphicon-menu-hamburger"></span></label>
</div>
<div class="setQuestion">
<h2>{{surveys[index].questionTitle}}</h2>
</div>
</div>
<div class="content-wrapper" class="container-fluid">
<div class="sidebar-left">
<div class="first">
<ul ng-repeat="cat in surveys[index].category" class="list-unstyled" ng-hide="checkSubCategoryValueIsNull.length">
<li class="category">
<a ng-click="expand=!expand">
<span class="glyphicon" ng-class="{'glyphicon-plus': !expand, 'glyphicon-minus': expand}">
{{cat.categoryName}}
</span>
</a>
</li>
<ul ng-repeat="subcategory in cat.categoryItemDto" class="list-unstyled">
<li ng-show="expand">
<label class="label-style-change">
<input type="checkbox" ng-click="toggleSelectionCheckbox(surveys[index], subcategory)" ng-model="subcategory.selectValue" ng-disabled="disableCheckbox">
<span class="subcategory-item" ng-disabled="disableCheckbox">{{subcategory.subCategoryName}}</span>
</label>
</li>
</ul>
</ul>
</div>
<div class="second">
<input type="button" name="Submit" value="Submit" ng-click="submitSelection()" ng-hide="hideSubmitButton" ng-disabled="!selections[index].length">
<input type="button" name="Edit" value="Edit" ng-click="EditSelection()" ng-show="hideEditButton">
</div>
</div>
<div class="portfolio">
<div id="main">
<div ng-view></div>
</div>
</div>
</div>
</body>
controller.js
(function() {
var app = angular.module("app.controllers", ["app.service"]);
app.controller("myCtrl", ["$scope", "$http", "$location", "$timeout", "surveyService", "Data",
function ($scope, $http, $location, $timeout, surveyService, Data) {
surveyService.getData(function(dataResponse) {
$scope.surveys = dataResponse;
$scope.selections = [];
/* create 2d array mannually */
var numInternalArrays = $scope.surveys.length;
for (var i = 0; i < numInternalArrays; i++) {
$scope.selections[i] = [];
};
$scope.index = 0;
var toggleCheckboxFlag = 0;
/* PRIVATE FUNCTION
for find value from selections array and replace it
*/
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
array.splice(index, 1);
toggleCheckboxFlag = 1;
}
});
}
$scope.toggleSelectionCheckbox = function (QuestionId, value) {
toggleCheckboxFlag = 0;
if (!value) return;
findAndRemove($scope.selections[$scope.index], 'categoryId', value.subCategoryId);
if (toggleCheckboxFlag != 1) {
$scope.selections[$scope.index].push({
questionId: QuestionId.questionId,
categoryId: value.subCategoryId,
categoryName: value.subCategoryName,
storeId: 1,
comment: ""
});
}
};
$scope.submitSelection = function() {
$scope.value = $scope.selections[$scope.index];
$scope.hideSubmitButton = true;
$scope.disableCheckbox = true;
$scope.hideEditButton = true;
$location.path("/question/1");
}
});
$scope.EditSelection = function() {
$scope.hideEditButton = false;
$scope.hideSubmitButton = false;
$scope.disableCheckbox = false;
$scope.value = false;
}
$scope.$watch('index', function (newValue, oldValue) {
if (newValue !== oldValue) Data.setIndex(newValue);
});
console.log("controller", Data.getIndex())
}]);
})();
app.js
var app = angular.module('app', ['ngRoute','app.service', 'app.controllers']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/question/1', {
templateUrl: 'views/first.html',
controller: 'sidebarCtrl'
})
.when('/question/2', {
templateUrl: 'views/second.html',
controller: 'mainCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
first.html
<div id="content-wrapper" ng-show="value">
<div class="col-lg-offset-1 col-lg-8 col-md-12 col-sm-12 col-xs-12">
<h2 class="subCategoryLabel"><span class="label">{{value[inc].categoryName}}</span></h2>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<button class="btnNext" ng-hide="inc == 0" ng-click="prev()">
<i class="glyphicon glyphicon-menu-left"></i>
</button>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<form name="myForm">
<div ng-repeat="item in surveys[index].optionCategoryItemDto" class="formStyle">
<label class="text-center">
<input type="radio" name="radio" id="{{item.itemId}}" ng-value="item.itemId" ng-model="selections[index][inc].answer" required>
{{item.itemName}}
</label>
</div>
<br/>
<br/>
</form>
</div>
<div class="col-lg-3 col-lg-offset-1 col-md-offset-1 col-md-3 col-sm-4 col-xs-4">
<button class="btnNext" ng-hide="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="next()">
<i class="glyphicon glyphicon-menu-right"></i>
</button>
<button class="btnNext" ng-show="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="nextQuestion()">
<i class="glyphicon glyphicon-forward"></i>
</button>
</div>
</div>
<div class="col-lg-offset-3 col-lg-4 col-md-offset-3 col-md-6 col-sm-offset-3 col-sm-6 col-xs-4">
<textarea type="text" id="text" class="form-control txtArea" ng-model="selections[index][inc].comment" placeholder="Write comment..."></textarea>
</div>
</div>
sidebarCtrl.js
in this controller i update $scope.index when we call nextQuestion(). here $scope.index increment by one and $watch function also get latest value of index. but myCtrl is not update. i wants to update myCtrl.
(function() {
var app = angular.module("app.controllers");
app.controller("sidebarCtrl", ['$scope', "$location", "Data", function($scope, $location, Data) {
$scope.inc = 0;
$scope.next = function() {
$scope.inc += 1;
}
$scope.prev = function() {
$scope.inc -= 1;
}
$scope.nextQuestion = function() {
$scope.index += 1;
$location.path("/question/2");
}
$scope.$watch('index', function (newValue, oldValue) {
console.log("SASAS", newValue)
if (newValue !== oldValue) Data.setIndex(newValue);
});
}]);
})();
service.js
(function() {
var app = angular.module("app.service", []);
app.service("surveyService", function($http) {
this.getData = function (callbackFunc) {
$http({
method: "GET",
data: {something: true},
contentType: 'application/json',
dataType: 'jsonp',
url: "http://localhost:8080/TheSanshaWorld/sfcms/fetch-survey-details"
}).success(function(data){
callbackFunc(data);
}).error(function(){
alert("error");
});
};
this.setData = function(value) {
if (confirm('Do you wanna to submit?')) {
$http.post("http://localhost:8080/TheSanshaWorld/sfcms/save-survey-result-data", value).success(function(data, status) {
window.open("../index.html","_self");
});
} else {
return false;
}
};
});
app.factory('Data', function () {
var data = {
Index: ''
};
return {
getIndex: function () {
return data.Index;
},
setIndex: function (index) {
data.Index = index;
console.log("service", data.Index)
}
};
});
})();
Because sidebarCtrl is nested within myCtrl, therefore you can reach myCtrl $scope.index from sidebarCtrl using it $scope.$parent.index,
Try it by test: add any parameter value to myCtrl $scope.name='Bob';
then log it in sidebarCtrl console.log($scope.$parent.name); you should see printed 'Bob'. Do the same with index.

how to make dynamic 5 star rating using angularjs?

I have 3 Questions each i have given 5 stars,after user submit i need to convert to 5 how to do this using this formula x1w1 + x2w2 + x3w3 ... xnwn/Total.
http://help.surveymonkey.com/articles/en_US/kb/What-is-the-Rating-Average-and-how-is-it-calculate.i have done something but its not right way i think so?
//--------------------------------------review controller--------------
.controller('ReviewCtrl', [
'$scope', '$http', '$location', '$window',
function($scope, $http, $location, $window) {
$scope.rating1 = {};
$scope.rating2 = {};
$scope.rating3 = {};
$scope.isReadonly = true;
$scope.rateFunctionone = function(rating) {
window.localStorage.setItem("rating1", rating);
};
$scope.rateFunctiontwo = function(rating) {
window.localStorage.setItem("rating2", rating);
};
$scope.rateFunctionthree = function(rating) {
window.localStorage.setItem("rating3", rating);
};
$scope.submit = function() {
var bookingid= window.localStorage.getItem("reviewbookingid");
var storeid = window.localStorage.getItem("reviewstoreid");
var cusname = window.localStorage.getItem("username").replace(/\"/g, "");
var rating1 = window.localStorage.getItem("rating1");
var rating2 = window.localStorage.getItem("rating2");
var rating3 = window.localStorage.getItem("rating3");
var totrating = (parseInt(rating1) + parseInt(rating2) + parseInt(rating3)) / 15;
console.log(totrating);
$http.get('******').success(function(data, response) {
var totcustomer = data.length + 1;
var totcustreview =data.length;
console.log(totcustreview);
if (data.length == 0) {
var caltotrating = (0 + totrating) / totcustomer;
} else
{
var caltotrating = (parseInt(data[0].Rating) + parseInt(totrating)) / totcustomer;
}
var credentials = {};
credentials = {
"Customet_Name": cusname,
"Timely_delivery": rating1,
"Quality_of_service": rating2,
"Value_for_money": rating3,
"Average": totrating,
"Rating": caltotrating,
"Comments": $scope.command,
"Booking_id": bookingid,
"Store_id": storeid
}
var scredentials = {};
scredentials = {
"S_Ratings": caltotrating,
"S_Noofpeoplegivenreview": totcustomer,
}
$http.put('***').success(function(data, status, headers, config, response) {
});
$http.post('***').success(function(data, status, headers, config, response) {
});
});
}
}
])
//---------------------------------------------------------------------
.directive("starRating", function() {
return {
restrict: "EA",
template: "<ul class='rating' ng-class='{readonly: readonly}'>" +
" <li ng-repeat='star in stars' ng-class='star' ng-click='toggle($index)'>" +
" <i class='ion-star'></i>" + //&#9733
" </li>" +
"</ul>",
scope: {
ratingValue: "=ngModel",
max: "=?", //optional: default is 5
onRatingSelected: "&?",
readonly: "=?"
},
link: function(scope, elem, attrs) {
if (scope.max == undefined) {
scope.max = 5;
}
function updateStars() {
scope.stars = [];
for (var i = 0; i < scope.max; i++) {
scope.stars.push({
filled: i < scope.ratingValue
});
}
};
scope.toggle = function(index) {
if (scope.readonly == undefined || scope.readonly == false) {
scope.ratingValue = index + 1;
scope.onRatingSelected({
rating: index + 1
});
}
};
scope.$watch("ratingValue", function(oldVal, newVal) {
if (newVal) {
updateStars();
}
});
}
};
})
<ion-content ng-controller="ReviewCtrl" >
<form data-ng-submit="submit()">
<div class="row">
<div class="col item item-divider">Timely Delivery </div>
<div class="col item item-divider">
<div star-rating ng-model="rating1" max="5" on-rating-selected="rateFunctionone(rating)"></div>
</div>
</div>
<br>
<div class="row">
<div class="col item item-divider">Quality of Service </div>
<div class="col item item-divider">
<div star-rating ng-model="rating2" max="5" on-rating-selected="rateFunctiontwo(rating)"></div>
</div>
</div>
<br>
<div class="row">
<div class="col item item-divider"> Value for Money </div>
<div class="col item item-divider">
<div star-rating ng-model="rating3" max="5" on-rating-selected="rateFunctionthree(rating)"></div>
</div>
</div>
<br>
<ul >
<li class="item item-checkbox">
<label class="checkbox checkbox-energized">
<input type="checkbox" ng-model="recommend" ng-true-value="'yes'" ng-false-value="'no'">
</label>
Would you recommend this dealer to your friends?
</li>
</ul>
<label class="item item-input item-floating-label" >
<span class="input-label">Say! how you feel</span>
<textarea placeholder="Say! how you feel" rows="4" ng-model="command"></textarea>
</label>
<div class="padding">
<button class="button button-full button-stable" type="submit" > Submit
</button>
</form>
</div>
</ion-content>
Use this RateIt for rating its quite easy you just need bower to install it and include the js and css.

ng-click ng-keypress passing form data not working

Im trying to send data from user input to display on the screen when button click.
The problem is that if i click on the button it simply passes to the next value without gathering the information and displaying in the screen. If i press ENTER it works how it should. i have searched all over internet several examples but simply couldnt get it to work. im using at the moment :
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
full html:
<div class="boxContent col-md-12">
<h1>{{lang.sec101.h1}}</h1>
<div class="col-md-12 lineBorder noPad" >
<div class="box1">
<p>
{{lang.sec101.title}}
</p>
</div>
<!-- dynamic form -->
<div class="col-md-12 borderBox boxLeft bg_box">
<form novalidate name="addForm">
<div class="boxLeft" ng-show="Question != ''">
<div ng-show="Question.infotip != 'yes'">
<h1 class="heading_left">{{Question.ask}}</h1>
</div>
<div ng-show="Question.infotip == 'yes'">
<h1 class="heading_left info">{{Question.ask}}
<span class="infotip yourData" tooltip-placement="top" tooltip-trigger="click" tooltip="{{Question.infotipText}}"></span>
</h1>
</div>
</div>
<div class="boxRight" ng-show="Question != ''">
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
</div>
<div class="boxRejestracjaInput">
<!-- <div id="legg-select" ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</div> -->
<div class="newSelect">
<label ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</label>
</div>
<input
ng-if="Question.type === 'text'"
type="{{Question.type}}"
name="institutionName"
class="inputName"
value="{{Question.value}}"
ng-model="value"
ng-minlength="{{Question.min}}"
ng-maxlength="{{Question.max}}"
ng-keypress="enter($event,value)"
placeholder="{{Question.placeholder}}"
ng-pattern="{{Question.pattern}}" />
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.minlength || addForm.institutionName.$error.maxlength">
Minimum {{Question.min}} znaków
</div> -->
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.maxlength">
Max {{Question.max}} znaków
</div> -->
<div class="custom-error institution" ng-show="addForm.institutionName.$error.pattern || addForm.institutionName.$error.maxlength || addForm.institutionName.$error.minlength">
{{Question.copy}}
</div>
</div>
</form>
</div>
<p>
{{lang.sec101.title2}}
</p>
<a href="rejestracja_10edit.html" class="btn btn-lg btn-default bt_edit" type="button">
{{lang.sec101.title3}}<span class="btn_bg_img"></span>
</a>
</div>
<div class="col-md-12 noPad" ng-repeat="sek in formOut">
<h3 class="daneHeading">{{sek.name}}</h3>
<div class="row">
<div class="col-md-12" >
<div class="col-md-4 col-sm-6 boxContent3 boxes" ng-repeat="row in sek.data">
<span class="leftBoxContrnt">{{row.shortAsk}}</h4></span>
<h4 class="rightBoxContrnt">{{row.value}}</h4>
</div>
</div>
</div>
</div>
<!-- <div class="row col-md-12" >
<h3 class="daneHeading">Hasło</h3>
</div>
<div class="row">
<div class="col-md-12 " >
<div class="col-md-4 col-sm-6 boxContent3">
<span class="leftBoxContrnt">Test</h4></span><span class="blueTxt"> *</span>
<h4 class="rightBoxContrnt">Test</h4>
</div>
</div>
</div> -->
</div>
my controller:
var app = angular.module('app', ['ngAnimate', 'ngCookies', 'ui.bootstrap', 'ngSanitize', 'nya.bootstrap.select', 'jackrabbitsgroup.angular-slider-directive']);
// var rej10_Controller = function($scope, $http, $cookieStore, $timeout, limitToFilter) {
app.controller('rej10_Controller', ['$scope', '$http', '$cookieStore', '$sce', '$timeout', 'limitToFilter',
function($scope, $http, $cookieStore, $sce, $timeout, limitToFilter) {
var view = 10,
arr,
data,
counterSection = 0,
counterAsk = 0;
$scope.opts = {};
$scope.slider_id = 'my-slider';
$scope.opts = {
'num_handles': 1,
'user_values': [0, 1],
'slider_min': 0,
'slider_max': 1,
'precision': 0,
};
/* language */
if (!$cookieStore.get('lang'))
$cookieStore.put('lang', 'pl');
var lang = $cookieStore.get('lang');
$scope.language = lang;
$scope.setLang = function(data) {
$cookieStore.put('lang', data);
$http.get('../widoki/json/lang/' + data + '/rej_' + view + '.json').
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn.sekcja[counterSection].data[counterAsk];
console.log($scope.lang);
}).
error(function(data, status, headers, config) {
console.log('error load json');
});
$scope.language = data;
};
/* get language pack */
$http({
method: 'GET',
url: '../widoki/json/lang/' + lang + '/rej_' + view + '.json'
}).
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
$scope.langLen = $scope.lang.formIn.length;
}).error(function(data, status, headers, config) {
console.log('error load json');
});
/* dynamic form */
$scope.enter = function(ev, d) {
if (ev.which == 13) {
$scope.addData(d);
}
};
$scope.addData = function(data) {
var newData = {};
/* latamy po id sekcji i po id pytania */
if (!$scope.formOut) {
$scope.formOut = [];
}
/* budowanie modelu danych wychodzcych */
newData = {
sekcja: counterSection,
name: $scope.lang.formIn[counterSection].name,
data: []
};
console.log(name);
if (!$scope.formOut[counterSection]) {
$scope.formOut.push(newData);
}
$scope.formOut[counterSection].data.push($scope.Question);
$scope.formOut[counterSection].data[counterAsk].value = data;
counterAsk++;
// zmieniamy sekcje
if (counterAsk == $scope.lang.formIn[counterSection].data.length) {
counterAsk = 0;
counterSection++;
}
if (counterSection == $scope.lang.formIn.length) {
$scope.Question = '';
/* zrobic ukrycie pola z formularza */
} else {
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
}
/* konwertowanie do jsona */
//var Json = angular.toJson($scope.formOut);
//console.log(Json);
};
$scope.submit = function() {
alert('form sent'); /* wysĹanie formularza */
};
$scope.getClass = function(b) {
return b.toString();
};
}
]);
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
app.config(['$tooltipProvider',
function($tooltipProvider) {
$tooltipProvider.setTriggers({
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur',
'never': 'mouseleave',
'show': 'hide'
});
}
]);
var ValidSubmit = ['$parse',
function($parse) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
var form = element.controller('form');
form.$submitted = false;
var fn = $parse(iAttrs.validSubmit);
element.on('submit', function(event) {
scope.$apply(function() {
element.addClass('ng-submitted');
form.$submitted = true;
if (form.$valid) {
fn(scope, {
$event: event
});
}
});
});
scope.$watch(function() {
return form.$valid
}, function(isValid) {
if (form.$submitted == false)
return;
if (isValid) {
element.removeClass('has-error').addClass('has-success');
} else {
element.removeClass('has-success');
element.addClass('has-error');
}
});
}
};
}
};
}
];
app.directive('validSubmit', ValidSubmit);
I cant figure out what is the problem.
Thanks in advance.
Try changing your ngClick button handler to an ngSubmit form handler and wiring that up. You didn't say what browser you're using, but most of them auto-submit forms on an ENTER keypress unless you trap it (which you aren't). Clicking a button won't do this.

Resources