weird behavior of ngrepeat in angularJS - angularjs

I am having issue with ng-repeat , its replacing all values with latest one.
E.g. I am adding a value to textbox then adding that value in ng-repeat div but its replacing all values with last value entered.
Here is Jsfiddle
https://jsfiddle.net/mahajan344/9bz4Lwxa/656/

This is happening because you have only one statusObj and you are modifying it every time someone clicks the Add New Status button. Delete the statusObj you have now, and have the AddNewStatus method create a new one each time:
var xyzApi = xyzApi || {
sayHello: function() {
return "hey there\n";
}
};
angular.module('demoApp', [])
.controller('MainController', MainController)
.provider('xyzApi', function XyzApiProvider() {
this.$get = function() {
var xyzApiFactory = {
otherFunction: function() {
//$log.log('other function called');
return 'other function \n';
}
};
//console.log(xyzApiFactory, xyzApi);
angular.merge(xyzApiFactory, xyzApi);
return xyzApiFactory;
};
});
function MainController(xyzApi) {
var vm = this;
vm.test = '';
vm.listOfStatus = [];
vm.showStatusError = false;
vm.statusText = "";
vm.sayHello = function() {
vm.test += xyzApi.sayHello() + xyzApi.otherFunction();
}
vm.AddNewStatus = function(statusText) {
if (statusText.length < 1) {
vm.showStatusError = true;
return;
} else {
vm.showStatusError = false;
}
var statusObj = {
StatusComment: statusText,
scId: 0,
scTimeStamp: new Date(),
JobNum: 0,
IsNew: 0,
};
vm.listOfStatus.push(statusObj);
vm.statusText = "";
};
vm.RemoveStatus = function(index) {
vm.listOfStatus.splice(index, 1);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
<div ng-app="demoApp" ng-controller="MainController as mainCtrl">
<pre>{{mainCtrl.test}}</pre>
<button ng-click="mainCtrl.sayHello()">
say hello!!
</button>
<div id="DivStatus">
<div class="form-group">
Status
<div class="col-md-3 col-sm-3 col-xs-12">
<input type="text" ng-model="mainCtrl.statusText" id="txtStatus" class="form-control col-md-7 col-xs-12">
<div class="text-danger error-message" id="txtStatusError" ng-show="showStatusError">Please enter new status</div>
</div>
<div class="col-md-3 col-md-3x col-sm-3 col-xs-12">
<input type="button" class="btn" ng-click="mainCtrl.AddNewStatus(mainCtrl.statusText)" value="Add New Status" />
</div>
</div>
<div class="form-group" ng-repeat="statusObj in mainCtrl.listOfStatus track by $index">
<div class="col-md-3 col-sm-3 col-xs-12">
<input type="text" value="{{statusObj.StatusComment}}" ng-disabled="true" class="form-control col-md-7 col-xs-12">
</div>
<span class="remove-record" ng-click="mainCtrl.RemoveStatus($index)" style="cursor:pointer"><i class="fa fa-times"></i></span>
</div>
</div>
</div>

Related

Send/Add CVV/CVN Field on Cybersource Flex Microform

I am using Flex Microform and was able to successfully render the Credit Card Iframe from Cybersource.
Now, the question is to Add/Send CVN/CVV details along with above request.
In the document, we can pass only three parameters in the createToken Method - CardType, CardExpirationYear, and CardExpirationMonth.
I couldn't find anything about sending/Adding CVN.
Please guide if anyone has done similar implementation where we can send CVN details from the Flex Form.
Html
---
<label id="cardNumber-label">Card Number</label>
<div id="number-container" class="form-control"></div>
<label for="securityCode-container">Security Code</label>
<div id="securityCode-container" class="form-control"></div>
--
</div>
<div class="form-row">
----
</form>
Js
var flex = new Flex(captureContext);
var microform = flex.microform({ styles: myStyles });
var number = microform.createField('number', { placeholder: 'Enter card number' });
var securityCode = microform.createField('securityCode', { placeholder: '•••' });
number.load('#number-container');
securityCode.load('#securityCode-container');
Ref: developer-guides
I think this is what you're looking for
https://developer.cybersource.com/docs/cybs/en-us/digital-accept-flex/developer/all/rest/digital-accept-flex/microform-integ/api_reference/class_Microform.html
Example:
<div class="container card">
<div class="card-body">
<h1>Checkout</h1>
<div id="errors-output" role="alert"></div>
<div class="form-group">
<label for="cardholderName">Name</label>
<input id="cardholderName" class="form-control" name="cardholderName" placeholder="Name on the card">
<label id="cardNumber-label">Card Number</label>
<div id="number-container" class="form-control"></div>
<label for="securityCode-container">Security Code</label>
<div id="securityCode-container" class="form-control"></div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="expMonth">Expiry month</label>
<select id="expMonth" class="form-control">
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="expYear">Expiry year</label>
<select id="expYear" class="form-control">
<option>2022</option>
<option>2023</option>
</select>
</div>
</div>
</div>
</div>
<script src="https://flex.cybersource.com/cybersource/assets/microform/0.11/flex-microform.min.js"></script>
<script>
$(document).ready(function() {
$('#submission-form').submit(function(e) {
e.preventDefault();
});
var form = document.querySelector('#submission-form');
var payButton = document.querySelector('#btnPay');
var flexResponse = document.querySelector('#SecureToken');
var expMonth = document.querySelector('#expMonth');
var expYear = document.querySelector('#expYear');
var errorsOutput = document.querySelector('#errors-output');
// the capture context that was requested server-side for this transaction
var captureContext = /*caputre context loaded here*/ ;
// setup
var flex = new Flex(captureContext);
var number = microform.createField('number', {
placeholder: 'Enter card number'
});
var securityCode = microform.createField('securityCode', {
placeholder: '•••'
});
number.load('#number-container');
securityCode.load('#securityCode-container');
payButton.addEventListener('click', function() {
var options = {
expirationMonth: expMonth.value,
expirationYear: expYear.value
};
microform.createToken(options, function(err, token) {
if (err) {
// handle error
} else {
flexResponse.value = JSON.stringify(token);
form.submit();
}
});
});
});
</script>

two way binding not working even with dot notation

I'm starting with AngularJS and I am using a controller variable to navigate an array of questions, and it is working when using nextQuestion function, index gets updated and the next question is shown in the view, but if I try to obtain the same value (index) in a different function, it always returns 0.
I have seen on other questions that you should use an object to contain the variable to not manipulate primitive types directly in the controller, but it still does not work.
My controller:
myApp.controller('SurveyController',['$scope','$http', '$location','$routeParams','surveyMetrics','DataService',function($scope,$http, $location,$routeParams,surveyMetrics,DataService){
console.log('LOADED QUIZ CONTROLLER');
var vm = this;
vm.scope = {
index: 0
};
vm.surveyMetrics = surveyMetrics;
vm.surveyQuestions = DataService.surveyQuestions;
vm.DataService = DataService;
/*
vm.getQuestions = function(){
$http.get('/api/questions').then(function(response){
$scope.questions = response.data;
});
}
*/
/*
vm.activateSurvey = function(){
surveyMetrics.changeState(true);
}
*/
vm.getCurrentIndex = function(){
return vm.scope.index;
}
vm.nextQuestion = function () {
console.log('NEXT QUESTION!');
console.log('NUMBER OF QUESTIONS: '+ vm.surveyQuestions.length);
var currentIndex = vm.getCurrentIndex();
var newIndex = currentIndex+1;
scope = {};
if (currentIndex == vm.surveyQuestions.length) {
newIndex = vm.surveyQuestions.length -1;
}
vm.scope.index = newIndex;
console.log('Inside Object: '+vm.scope)
console.log('vm.index'+vm.scope.index);
console.log('vm.indexFunction'+vm.getCurrentIndex());
}
/*
vm.previousQuestion = function () {
console.log('PREVIOUS QUESTION!');
console.log('NUMBER OF QUESTIONS: '+ vm.surveyQuestions.length);
if (vm.scope.index == 0) {
vm.scope.index = 0;
}else{
vm.scope.index--;
}
}
*/
vm.activeSurveyQuestion = function(questionId,index){
console.log('question id and index',questionId,index);
if (questionId == index) {
var navBtn = document.getElementById('navBtn_'+index);
navBtn.classList.add('active');
}
}
vm.navigateSurvey = function () {
var answerPane = document.getElementById('answer-pane');
document.onkeydown = function (e) {
console.log('INSIDE KEYDOWN: ')
e.preventDefault();
var pressedKey = e.keyCode;
console.log('PRESSED KEY IN SURVEY: ' + pressedKey);
if (pressedKey === rightArrow) {
console.log('survey - right arrow pressed');
document.getElementById('nextQuestionBtn').click();
console.log('FUCKING INDEX FML!: '+vm.getCurrentIndex()+' | '+vm.scope.index);
var questionType = DataService.getQuestionType(vm.scope.index);
console.log('Survey Controller: question type: '+questionType);
}
if (pressedKey === leftArrow) {
console.log('survey - left arrow pressed');
document.getElementById('previousQuestionBtn').click();
}
(...)
My View:
<!--Satisfaction Survey-->
<div ng-controller="SurveyController as survey" ng-init="survey.getSurvey();">
<!--
<p ng-repeat="question in survey.surveyQuestions" ng-show ="survey.surveyMetrics.surveyActive">
{{question.question}}
</p>
-->
<!--Survey Modal -->
<div class="modal fade" id="surveyModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="text-center"> Customer Satisfaction Survey</div>
<div class="modal-header">
<h4 class="modal-title">{{survey.surveyQuestions[survey.getCurrentIndex()].question}}</h4>
</div>
<div class="modal-body survey" id="answer-pane">
<div class="row">
<div class="col-sm-2 survey-left-arrow" ng-click="survey.previousQuestion();" id="previousQuestionBtn">
<p>‹</p>
</div>
<div class="col-sm-8">
<!-- <p ng-repeat="answer in survey.surveyQuestions[survey.index].answers">{{answer}}</p> -->
<p ng-repeat="answer in survey.surveyQuestions[survey.getCurrentIndex()].answers">
<button type="button" class="btn" id="answerId_{{survey.getCurrentIndex()}}"
ng-class="{'survey-check-box': (survey.surveyQuestions[survey.getCurrentIndex()].type !== 'SingleChoice'),
'survey-btn_{{($index+1)}}': (survey.surveyQuestions[survey.getCurrentIndex()].type === 'SingleChoice')}">
<input type="checkbox" ng-if="survey.surveyQuestions[survey.getCurrentIndex()].type !== 'SingleChoice'"> {{answer}}
</button>
</p>
</div>
<div class="col-sm-2 survey-right-arrow " ng-click="survey.nextQuestion();" id="nextQuestionBtn">
<p>›</p>
</div>
</div>
</div>
<div class="text-center">
<strong> <p>Question: {{survey.surveyQuestions[survey.scope.index].questionNum}} of {{survey.surveyQuestions.length}}</p> </strong>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<!-- <nav aria-label="Survey navigation">
<ul class="pagination pagination-sm justify-content-center">
<div ng-repeat="question in survey.surveyQuestions" >
<li class="page-item">
<a class="page-link" id = "navBtn_$index" ng-click="survey.index = $index">{{question.id}}</a>
</li>
</div>
</ul>
</nav> -->
</div>
</div>
I would like for the controller to change the variable and the view to update accordingly
Thank you for your time and thank you in advance.
It's 'survey.scope.index' not 'survey.index' in your HTML. I think you may be unclear the difference between using 'this' and '$scope'. You're mixing the two together which is not necessary. I would suggest removing 'scope' and just reference it in your HTML as 'survey.index'.

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.

AngularJS: upload file inside modal-ui-bootstrap

I have an angular modal-ui, in it I upload file. The problem is that for some reason the <input> of the file doesn't triggers the app directive. The directive returns the file name and size when the <input> being changed.
this is the result I want to get:
example
I really tried already any thing, but still for some reason I can't see in the <span> the file name.
The html file :
<form novalidate ng-submit="add(Form.$valid)" name="Form">
<div class="modal-header col-lg-12">
<h3 class="col-lg-4 col-lg-offset-4">add file</h3>
</div>
<div class="modal-body">
<div class="panel-body">
<div class="row">
<div class="form-group col-lg-8" ng-class="{'has-error': notPass && Form.fileName.$invalid}">
<label class="control-label label-add-card" for="fileName">name</label>
<input class="input-add-card form-control " id="fileName" name="fileName" type="text" ng-model="fileName" ng-pattern="/^[a-z1-9]{10,}$/" ng-required="true">
<p ng-show="notPass && Form.fileName.$invalid" class="help-block">not good</p>
</div>
</div>
<div class="row">
<div class="form-group col-lg-8" ng-class="{'has-error':notPass && Form.fileExplain.$invalid}">
<label class="control-label label-add-card" for="fileExplain">explain</label>
<textarea class="input-big form-control " id="fileExplain" name="fileExplain" type="text" ng-model="fileExplain" ng-pattern="/^[a-z1-9]{1,}$/" ng-required="true"></textarea>
<p ng-show="notPass && Form.fileExplain.$invalid" class="help-block">not good</p>
</div>
</div>
<div>
<div class="form-group col-lg-12" ng-class="{'has-error':notPass && Form.uploadDownloads.$invalid}">
<input ng-model="uploadDownloads" type="file" fd-input file-name="fileName" />
<input class="btn btn-primary" type="button" value="choose" onclick="$(this).parent().find('input[type=file]').click();"/> <!-- on button click fire the file click event -->
<span class="badge badge-important">{{fileName}}</span>
<p ng-show="notPass && Form.uploadDownloads.$invalid" class="help-block">please choose</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success col-lg-12 btn-modal-costume">add</button>
</div>
</form>
the modal controller:
/**
* Created by Ariel on 22/11/2015.
*/
app.controller('uploadDownloadsController',function($scope,$modalInstance ){
app.directive('fdInput', fdInput);
function fdInput() {
return {
scope: {
fileName: '='
},
link: function(scope, element, attrs) {
element.on('change', function(evt) {
var files = evt.target.files;
console.log(files[0].name);
console.log(files[0].size);
scope.fileName = files[0].name;
scope.$apply();
});
}
}
};
$scope.fileName = '';
$scope.add = function(valid){
if(valid){
$scope.data = 'none';
var f = document.getElementById('uploadDownloads').files[0];
var r = new FileReader();
r.onloadend = function(e){
$scope.data = e.target.result;
$scope.notPass = false;
$modalInstance.close({
'data':$scope.data,
'fileName':$scope.fileName,
'fileExplain':$scope.fileExplain
});
};
/*activate the onloadend to catch the file*/
r.readAsBinaryString(f);
} else {
$scope.notPass = true;
}
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
});
here is how I have done it :
the html :
<form novalidate ng-submit="add(Form.$valid)" name="Form">
.
.
.
<div>
<div class="form-group col-lg-12" ng-class="{'has-error':notPass && Form.uploadDownloads.$invalid}">
<input ng-model="uploadDownloads" class="form-control-file" id="uploadDownloads" type="file" fd-input file-names="fileNames" />
<input class="btn btn-primary" type="button" value="choose" ng-click="choose()"/> <!-- on button click fire the file click event -->
<span class="badge badge-important">{{fileNames}}</span>
<p ng-show="notPass && Form.uploadDownloads.$invalid" class="help-block">you have to choose file</p>
</div>
</div>
.
.
.
</form>
I built a direcvtive to show thee file name dorring the upload:
/*get and shows the file name*/
app.directive('fdInput', function($timeout){
return {
scope: {
fileNames: '='
},
link:function(scope, element, attrs) {
$timeout(element.on('change', function(evt) {
var files = evt.target.files;
scope.fileNames = files[0].name;
scope.$apply();
}),0);
}
}
});
and this is the upload file controller:
app.controller('uploadDownloadsController',function($scope,$modalInstance,$timeout){
$scope.fileNames = '';
$scope.choose = function(){
$('#uploadDownloads').trigger('click');
};
$scope.add = function(valid){
if(valid){
$scope.data = 'none';
$scope.notPass = false;
/*this catches the file*/
var fileInput = document.getElementById('uploadDownloads');
var file = fileInput.files[0];
/* to send the file and the other inputs about it, need to use formData type*/
var formData = new FormData();
formData.append('file', file);
formData.append('fileName', $scope.fileName);
formData.append('fileExplain', $scope.fileExplain);
console.log(formData);
$modalInstance.close(formData);
} else {
$scope.notPass = true;
}
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
});

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.

Resources