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??
Related
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.
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>" + //★
" </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.
I tried to alias the AngularJS controller in the view, but for some strange reason - it does not seem to respond when I prefix the methods and properties - any idea what might be causing it?
Here's my view (I'm using it with Laravel 5.1):
#extends('admin.template.layout-login')
#section('content')
<div class="row">
<div class="large-6 medium-8 columns large-offset-3 medium-offset-2" ng-controller="LoginController as login">
<form
name="htmlForm"
class="panel hide"
ng-submit="login.submit()"
ng-class="{ 'show-block' : !login.isRequestCompleted() }"
novalidate
>
<label for="username">
Username: *
<ng-messages
for="htmlForm.username.$error"
class="hide"
ng-class="{ 'show-inline' : login.isSubmitted() }"
>
<ng-message
when="required"
class="warning"
>Please provide your email address</ng-message>
<ng-message
when="email"
class="warning"
>Invalid email address</ng-message>
<ng-message
when="unsuccessful"
class="warning"
>Incorrect login details</ng-message>
<ng-message
when="suspended"
class="warning"
>Your account has been suspended</ng-message>
</ng-messages>
</label>
<input
type="email"
ng-model="formData.username"
name="username"
id="username"
required
>
<label for="password">
Password: *
<ng-messages
for="htmlForm.password.$error"
class="hide"
ng-class="{ 'show-inline' : login.isSubmitted() }"
>
<ng-message
when="required"
class="warning"
>Please provide your password</ng-message>
<ng-message
when="password"
class="warning"
>Invalid password</ng-message>
</ng-messages>
</label>
<input
type="password"
ng-model="formData.password"
name="password"
id="password"
required
password
>
<label for="remember">
<input
type="checkbox"
ng-model="formData.remember"
name="remember"
id="remember"
> Remember Me
</label>
<input
type="submit"
class="small button"
value="SEND ENQUIRY"
ng-if="!login.isOutForDelivery()"
>
<button
type="button"
class="small button"
disabled
ng-if="login.isOutForDelivery()"
>
PLEASE WAIT <i class="fa fa-spinner fa-spin"></i>
</button>
</form>
<div
class="hide"
ng-class="{ 'show-block' : login.isRequestCompleted() }"
ng-bind-html="login.trustAsHtml(confirmation)"
></div>
</div>
</div>
#endsection
and here's the AngularJS controller module:
(function(window, angular, app) {
"use strict";
app.controller(
'LoginController',
[
'$scope',
'$controller',
'$window',
function(
$scope,
$controller,
$window
) {
angular.extend(this, $controller('FormController', { $scope: $scope }));
$scope.submit = function() {
if ( ! $scope.isValid()) return false;
$scope.data = {
username : $scope.formData.username,
password : $scope.formData.password
};
$scope.submitRequest(
'/admin',
$scope.data
)
.success(function(data, status, headers, config, statusText) {
$window.location.href = data.url;
})
.error(function(data, status, headers, config, statusText) {
$scope.validation(data);
$scope.endOutForDelivery();
return false;
});
};
}
]
);
})(window, window.angular, window.CmdSystem.App);
Plus the FormController that the previous extends:
(function(window, angular, app) {
"use strict";
app.controller(
'FormController',
[
'$scope',
'RequestService',
'ContentService',
function(
$scope,
RequestService,
ContentService
) {
$scope.outForDelivery = false;
$scope.requestCompleted = false;
$scope.submitRequest = function(url, formData) {
$scope.outForDelivery = true;
return RequestService.post(url, formData);
};
$scope.responseReceived = function() {
$scope.requestCompleted = true;
$scope.outForDelivery = false;
};
$scope.isResponseReceived = function() {
return $scope.requestCompleted && ! $scope.outForDelivery;
};
$scope.endOutForDelivery = function() {
$scope.outForDelivery = false;
};
$scope.trustAsHtml = ContentService.trustAsHtml;
$scope.isValid = function() {
return $scope.htmlForm.$valid;
};
$scope.isSubmitted = function() {
return $scope.htmlForm.$submitted &&
! $scope.isRequestCompleted();
};
$scope.isRequestCompleted = function() {
return $scope.requestCompleted;
};
$scope.isOutForDelivery = function() {
return $scope.outForDelivery;
};
$scope.validation = function(data) {
angular.forEach(data, function(value, key) {
this[key].$error[value] = true;
}, $scope.htmlForm);
};
}
]
);
})(window, window.angular, window.CmdSystem.App);
None of the methods are on the controller. They're all defined on the $scope. So you can't access them using the login alias, which refers to the controller, not to the scope.
If you want to be able to call
login.foo()
from the view, then the method must be set on the controller, not on the scope:
this.foo = function() { ... };
I have been stuck on this for a while. I have a Job class that has multiple ChangeOrders and Purchase Orders. I can create a New Job without problems. I use the same code to Post the New CO and PO. The problem is the values are not binding to there controllers. The difference between the New Job and CO/PO is I am using $rootScope and ngStorage to insert the JobId into the CO/PO modals.
Purchase Order Modal
//New PurchaseOrder Modal
$scope.NewPurchaseOrderModal = function () {
var modalInstance = $modal.open({
templateUrl: 'views/modals/NewPurchaseOrderModal.html',
controller: 'NewPurchaseOrderModalInstanceCtrl',
windowClass: 'large-Modal',
resolve: {
p: function () {
return $scope.p;
}
}
});
};
Purchase Order POST
//Post New Purchase Orders
$scope.submitPO = function () {;
$scope.job = {};
alert($scope.PONumber);
var data = {
JobId: $scope.job.JobId,
PONumber: $scope.PONumber,
PODate: $scope.PODate,
POAmount: $scope.POAmount,
POLastPrintDate: $scope.POLastPrintDate,
POEmail: $scope.POEmail,
POPrint: $scope.POPrint,
POFaxNumber: $scope.POFaxNumber,
PONotes: $scope.PONotes,
POCreatedBy: $scope.POCreatedBy,
PODeliveryDate: $scope.PODeliveryDate,
POShipVia: $scope.POShipVia,
POShowPrices: $scope.POShowPrices,
POCostCode: $scope.POCostCode,
POApprovedNumber: $scope.POApprovedNumber,
POBackorder: $scope.POBackorder,
}
$http.post('/api/apiPurchaseOrder/PostNewPurchaseOrder', data).success(function (data, status, headers) {
console.log(data);
$scope.cancelNewPurchaseOrderModal();
});
};
});
Purchase Order View
<div class="container" style="margin-top:20px" ng-controller="POCtrl">
<form ng-submit="submitPO()" enctype="multipart/form-data">
<fieldset>
<tabset>
<tab heading="Cover">
<div class="col-xs-12" style="margin-top:10px">
<div class="inline-fields" style="" ng-show="true">
<label>JobId:</label>
<input style="width:150px;" ng-model="job.JobId" type="text" />
</div>
<div class="inline-fields">
<label></label>
<input style="width:150px;margin-left:81px" ng-model="job.JobName" type="text" />
<label style="margin-left:268px">Number:</label>
<input style="width:150px" ng-model="PONumber" type="text" />
</div>
<div class="inline-fields">
<label style="margin-left:48px">Attn:</label>
<input style="width:150px;" ng-model="ChangeOrderAttn" type="text" />
<label style="margin-left:291px">Date:</label>
<input style="width:150px" ng-model="PODate" type="date" />
</div>
<div class="inline-fields">
<label style="margin-left:39px">Email:</label>
<input style="width: 150px;" ng-model="POEmail" type="text" />
<label style="margin-left:217px">GC Ref Number:</label>
<input style="width:150px" ng-model="POApprovedNumber" type="text" />
</div>
<div class="inline-fields">
<label style="margin-left:52px">Fax:</label>
<input style="width: 150px; " ng-model="POFaxNumber" type="text" />
<label style="margin-left:233px">Delivery Date:</label>
<input style="width:150px" ng-model="PODeliveryDate" type="date" />
</div>
<div class="inline-fields">
<label style="margin-left: 438px">Approved Amount:</label>
<input style="width:150px" ng-model="ChangeOrderApprovedAmount" type="text" />
</div>
</div><!--End col-xs-6-->
<div class="col-xs-12">
<div class="inline-fields" style="margin-top:30px;margin-left:2px">
<label>Created By:</label>
<input style="width:635px" ng-model="POCreatedBy" type="text" />
</div>
<div class="inline-fields" style="margin-left:37px">
<label>Notes:</label>
<textarea style="width:635px;height:200px" ng-model="PONotes"></textarea>
</div>
<div class="inline-fields" style="margin-top:10px;margin-left:509px">
<label>Amount:</label>
<input style="width:150px" ng-model="POAmount" type="text" />
</div>
</div>
<div class="col-xs-12" style="margin-top:30px;padding-bottom:20px">
<input style="margin-left:435px;width:75px;margin-right:25px" ng-click="printEditChangeOrderModal()" type="button" value="Print" go-click="#" />
<input style="margin-right:25px;width:75px" type="submit" value="Save" go-click="#" />
<input style="width:75px" type="button" ng-click="cancelNewPurchaseOrderModal();" value="Exit" go-click="#" />
</div><!--End col-xs-12-->
</tab><!--End Cover Content-->
<tab heading="Details">...</tab>
<tab heading="Items">...</tab>
</tabset><!--End Tab Content-->
</fieldset><!--End Fieldset-->
</form>
Function to set the JobId in sessionStorage
//Sync Table Selections / sessionStorage
$scope.selectedJob = $sessionStorage.$default($scope.jobArray[1]);
$scope.selectJob = function (job) {
$rootScope.job = job;
angular.extend($scope.selectedJob, job);
console.log($rootScope.job);
};
$scope.clearSelectedJob = function () {
$sessionStorage.$reset();
};
table to select which Job is set in Storage
<div id="scrollArea" style="margin-top:40px" ng-controller="JobCtrl">
<table class=" table table-striped table-hover">
<thead> <tr><th>No</th><th>Name</th></tr></thead>
<tbody>
<tr ng-repeat="job in jobArray" class="pointer no_selection" ng-class="{highlight: job.JobNumber===selectedJob.JobNumber}">
<td ng-dblclick="EditJobModal(job.JobId)" ng-click="selectJob(job)">{{job.JobNumber}}</td>
<td ng-dblclick="EditJobModal(job.JobId)" ng-click="selectJob(job)">{{job.JobName}}</td>
</tr>
</tbody>
</table>
</div><!--End Job Table-->
PO Controller
'use strict';
app.controller('POCtrl', function ($scope, $rootScope, $resource, $http, $filter,
$q, $modal, PO, POGet, POFactory, notificationFactory) {
//New PurchaseOrder Modal
$scope.NewPurchaseOrderModal = function () {
var modalInstance = $modal.open({
templateUrl: 'views/modals/NewPurchaseOrderModal.html',
controller: 'NewPurchaseOrderModalInstanceCtrl',
windowClass: 'large-Modal',
resolve: {
p: function () {
return $scope.p;
}
}
});
};
//Edit PurchaseOrder Modal
$scope.EditPurchaseOrderModal = function (id) {
$.get('/api/apiPurchaseOrder/' + id, function (data) {
$scope.items = data;
var modalInstance = $modal.open({
templateUrl: 'views/modals/EditPurchaseOrderModal.html',
controller: 'EditPurchaseOrderModalInstanceCtrl',
windowClass: 'large-Modal',
resolve: {
items: function () {
return $scope.items;
}
}
});
});
};
//GET PurchaseOrders
POGet.query().then(function (data) {
$scope.poArray = data;
}, function (reason) {
errorMngrSvc.handleError(reason);
});
//Post New Purchase Orders
$scope.submitPO = function () {;
$http.post('/api/apiPurchaseOrder/PostNewPurchaseOrder', $scope.data).success(function (data, status, headers) {
$scope.cancelNewPurchaseOrderModal();
});
};
//$scope.submitPO = function () {;
// $scope.job = {};
// alert($scope.PONumber);
// var data = {
// JobId: $scope.job.JobId,
// PONumber: $scope.PONumber,
// PODate: $scope.PODate,
// POAmount: $scope.POAmount,
// POLastPrintDate: $scope.POLastPrintDate,
// POEmail: $scope.POEmail,
// POPrint: $scope.POPrint,
// POFaxNumber: $scope.POFaxNumber,
// PONotes: $scope.PONotes,
// POCreatedBy: $scope.POCreatedBy,
// PODeliveryDate: $scope.PODeliveryDate,
// POShipVia: $scope.POShipVia,
// POShowPrices: $scope.POShowPrices,
// POCostCode: $scope.POCostCode,
// POApprovedNumber: $scope.POApprovedNumber,
// POBackorder: $scope.POBackorder,
// }
// $http.post('/api/apiPurchaseOrder/PostNewPurchaseOrder', data).success(function (data, status, headers) {
// console.log(data);
// $scope.cancelNewPurchaseOrderModal();
// });
//};
});//End POCtrl
app.controller('NewPurchaseOrderModalInstanceCtrl', function ($scope, $modalInstance) {
$scope.cancelNewPurchaseOrderModal = function () {
$modalInstance.dismiss('cancel');
};
});
app.controller('EditPurchaseOrderModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.cancelEditPurchaseOrderModal = function () {
$modalInstance.dismiss('cancel');
};
});
Job Controller
'use strict';
app.controller('JobCtrl', function ($scope, $rootScope, $resource, $route, $http, $filter,
$q, $modal, $sessionStorage, Job, JobGet, jobFactory, notificationFactory) {
//New Job Modal
$scope.NewJobModal = function () {
var modalInstance = $modal.open({
templateUrl: 'views/modals/NewJobModal.html',
controller: 'NewJobModalInstanceCtrl',
windowClass: 'large-Modal',
resolve: {
p: function () {
return $scope.p;
}
}
});
};
$scope.EditJobModal = function (id) {
$.get('/api/apiJob/' + id, function (data) {
$scope.items = data;
var modalInstance = $modal.open({
templateUrl: 'views/modals/EditJobModal.html',
controller: 'EditJobModalInstanceCtrl',
windowClass: 'large-Modal',
resolve: {
items: function () {
return $scope.items;
}
}
});
});
};
//GET Jobs
$scope.jobArray = {};
JobGet.query().then(function (data) {
$scope.jobArray = data;
}, function (reason) {
errorMngrSvc.handleError(reason);
});
//Post New Job
$scope.submitJob = function () {
var data = {
GeoAreaId: $scope.newItems.GeoAreaId,
JobTypeId: $scope.newItems.JobTypeId,
JobClassId: $scope.newItems.JobClassId,
CustomerId: $scope.newItems.CustomerId,
JobId: $scope.newItems.JobId,
JobNumber: $scope.newItems.JobNumber,
JobName: $scope.newItems.JobName,
JobDescription: $scope.newItems.JobDescription,
JobOriginalContract: $scope.newItems.JobOriginalContract,
JobBillingDate: $scope.newItems.JobBillingDate,
JobTotalCO: $scope.newItems.JobTotalCO,
JobRevisedContract: $scope.newItems.JobRevisedContract,
}
$http.post('/api/apiJob/PostNewJob', data).success(function (data, status, headers) {
console.log(data);
$scope.cancelNewJobModal();
$scope.$evalAsync(function () {
$scope.data;
});
});
};
//Update Job
$scope.updateJob = function (job) {
jobFactory.updateJob(job).success(successCallback)
.error(errorCallback);
console.log(job);
$scope.cancelEditJobModal();
$scope.$evalAsync(function () {
$scope.job;
});
};
var successCallback = function (job, status, headers, config) {
notificationFactory.success();
};
var errorCallback = function (job, status, headers, config) {
notificationFactory.error(job.ExceptionMessage);
};
//Sync Table Selections / sessionStorage
$scope.selectedJob = $sessionStorage.$default($scope.jobArray[1]);
$scope.selectJob = function (job) {
$rootScope.job = job;
angular.extend($scope.selectedJob, job);
console.log($rootScope.job);
};
$scope.clearSelectedJob = function () {
$sessionStorage.$reset();
};
$scope.newItems = {};
//Typeahead New Job Customer select
$scope.selectNewCustomer = function (customer) {
$scope.newItems.CustomerId = customer.CustomerId;
$scope.newItems.Customer.CustomerName = customer.CustomerName;
$scope.newItems.Customer.CustomerAddress = customer.CustomerAddress;
$scope.newItems.Customer.CustomerCity = customer.CustomerCity;
$scope.newItems.Customer.CustomerState = customer.CustomerState;
$scope.newItems.Customer.CustomerZipcode = customer.CustomerZipcode;
$scope.newItems.Customer.CustomerPhoneNumber = customer.CustomerPhoneNumber;
$scope.newItems.Customer.CustomerFaxNumber = customer.CustomerFaxNumber;
$scope.newItems.Customer.CustomerWebsite = customer.CustomerWebsite;
$scope.newItems.Customer.CustomerOtherShit = customer.CustomerOtherShit;
$scope.newItems.Customer.CustomerHidden = customer.CustomerHidden;
$scope.newItems.Customer.CustomerPM = customer.CustomerPM;
$scope.newItems.Customer.CustomerAdmin = customer.CustomerAdmin;
$scope.newItems.Customer.CustomerAccountant = customer.CustomerAccountant;
};
});//End Job Controller
app.controller('NewJobModalInstanceCtrl', function ($scope, $modalInstance) {
$scope.cancelNewJobModal = function () {
$modalInstance.dismiss('cancel');
};
});
app.controller('EditJobModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.cancelEditJobModal = function () {
$modalInstance.dismiss('cancel');
};
});
I'd change to be handled everything in a single model which is easier to:
$scope.submitPO = function () {
$scope.data.jobId = $rootscope.job.id; //make sense?
$http.post('/api/apiPurchaseOrder/PostNewPurchaseOrder', $scope.data).success(function (data, status, headers) {
$scope.cancelNewPurchaseOrderModal();
});
};
the view:
<div class="inline-fields" style="" ng-show="true">
<label>JobId:</label>
<input style="width:150px;" ng-model="data.job.JobId" type="text" />
</div>
.....
<div class="inline-fields">
<label style="margin-left:48px">Attn:</label>
<input style="width:150px;" ng-model="data.ChangeOrderAttn" type="text" />
<label style="margin-left:291px">Date:</label>
<input style="width:150px" ng-model="data.PODate" type="date" />
</div>
and remove this $scope.job = {}; from your submit function, it looks like you are 'reseting' the job to an empty object
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.