Second controller won't work in my angular js - javascript

I search all on how to have two controllers, but it won't work. Is there anything wrong in my HTML? Is there anything wrong in my script?
Javascript code:
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = [];
$scope.addItem = function () {
$scope.errortext = "";
if (!$scope.addMe) {return;}
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe);
} else {
$scope.errortext = "The item is already in your shopping list.";
}
}
$scope.removeItem = function (x) {
$scope.errortext = "";
$scope.products.splice(x, 1);
}
});
var topics = angular.module("myList", []);
topics.controller("topicCtrl", function($scope) {
$scope.products = [];
$scope.addItem = function () {
$scope.errortext = "";
if (!$scope.addMe) {return;}
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe);
} else {
$scope.errortext = "The item is already in your shopping list.";
}
}
$scope.removeItem = function (y) {
$scope.errortext = "";
$scope.products.splice(x, 1);
}
});
angular.bootstrap(document.getElementById("app2"), ['myList']);
function addElement(value)
{
var dropdown = document.getElementById("OperationType");
var current_value = dropdown.options[dropdown.selectedIndex].value;
if (current_value == "Others") {
document.getElementById("OperationNos").style.display = "block";
}
else {
document.getElementById("OperationNos").style.display = "none";
}
}
function addElement2(value)
{
var dropdown = document.getElementById("topic");
var current_value = dropdown.options[dropdown.selectedIndex].value;
if (current_value == "Others") {
document.getElementById("usr").style.display = "block";
}
else {
document.getElementById("usr").style.display = "none";
}
}
HTML CODE:
<!--STANDARDS -->
<td>
<div ng-app="myShoppingList" ng-controller="myCtrl" id="app1" class="panel panel-default" style="max-width:400px;">
<div class="panel-heading">
<h3>
<select name="type" class="form-control" id="OperationType" onchange="addElement(this.value)" name="location">
<option value="Teacher">Teacher</option>
<option value="Coordinator">Coordinator</option>
<option value="Others">Others</option>
</select>
<input type="text" id="OperationNos"style="border: none;"class="form-control" placeholder="Input Title" value="{{x}}" >
</h3>
</div>
<div class="panel-body">
<ul class="list-group">
<li ng-repeat="x in products" class="list-group-item">
<input type="text" style="border: none;"class="form-control" value="{{x}}" id="usr">
<span ng-click="removeItem($index)" style="cursor:pointer;" class="text-right">×</span>
</li>
</ul>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-md-12">
<div class="input-group">
<input type="text" class="form-control" ng-model="addMe" placeholder="Add description">
<span class="input-group-btn">
<button class="btn btn-secondary btn-success" ng-click="addItem()" type="button">Add</button>
</span>
</div>
</div>
</div>
<p class="w3-padding-left w3-text-red">{{errortext}}</p>
</div>
</div>
</td>
<!-- END OF STANDARDS -->
<!--TOPICS -->
<td>
<div ng-app="myList" ng-controller="topicCtrl" id="app2" class="panel panel-default" style="max-width:400px;">
<div class="panel-heading">
<h3>
<select name="type" class="form-control" id="topic" onchange="addElement2(this.value)" name="topic">
<option value="Teacher">Teacher</option>
<option value="Coordinator">Coordinator</option>
<option value="Others">Others</option>
</select>
<input type="text" id="topics"style="border: none;"class="form-control" placeholder="Input Title" value="{{y}}" ></h3>
</div>
<div class="panel-body">
<ul class="list-group">
<li ng-repeat="y in products" class="list-group-item">
<input type="text" style="border: none;"class="form-control" value="{{y}}" id="usr">
<span ng-click="removeItem($index)" style="cursor:pointer;" class="text-right">×</span>
</li>
</ul>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-md-12">
<div class="input-group">
<input type="text" class="form-control" ng-model="addMe" placeholder="Add description">
<span class="input-group-btn">
<button class="btn btn-secondary btn-success" ng-click="addItem()" type="button">Add</button>
</span>
</div>
</div>
</div>
<p class="w3-padding-left w3-text-red">{{errortext}}</p>
</div>
</div>
</td>
<!-- END OF TOPICS -->

See the angularjs doc
only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application.
To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead.
AngularJS applications cannot be nested within each other.
Do not use a directive that uses transclusion on the same element as ngApp. This includes directives such as ngIf, ngInclude and ngView. Doing this misplaces the app $rootElement and the app's injector, causing animations to stop working and making the injector inaccessible from outside the app.

Related

Event Delegation in identical divs

I am very new to event delegation and I'm having trouble selecting the correct div to change. I have a partial view that can be displayed multiple times on a webpage. However, when it is displayed multiple times, the JavaScript only works for the first instance of the partial view. So I tried to use event delegation to solve my problem but it still only works on the first instance. I think it might be anytime I select by Id, since they share ids, it is selecting only the first id it sees and thus only working on the first instance of the partial view. Here is my Partial View's HTML:
<div id="AddMedia">
<form>
<div class="container">
<div class="form-row">
<div class="col-6 dropdown my-2 px-0">
<label class="control-label">Source:<span class="text-danger ml-1">*</span></label>
<select id="SourceFromSelect" asp-for="Medias.SourceFrom" asp-items="Html.GetEnumSelectList(typeof(SourceFromEnum))" style="width:85%;" class="btn border-dark" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<option class="dropdown-item" selected>Select</option>
</select>
<span asp-validation-for="Medias.SourceFrom" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="col-5">
<div id="MediaFile" class="form-group">
<label for="exampleFormControlFile1">Pick a File</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1">
</div>
<div id="MediaLink" class="form-group">
<label for="url">Link the Media</label>
<input type="url" class="form-control" id="exampleFormControlFile1">
</div>
</div>
</div>
</div>
</form>
</div>
And here is the script for it:
document.getElementById("MediaFile").style.display = "none";
const addMedia = document.querySelector("#AddMedia")
addMedia.addEventListener('change', function (e) {
if (e.target.getAttribute('id') === 'SourceFromSelect') {
changeFile(e);
}
});
function changeFile(e) {
// $("#SourceFromSelect").change(function () {
console.log(e.target)
var e = document.getElementById("SourceFromSelect");
var strUser = e.options[e.selectedIndex].text;
if (strUser == "Phone or Computer") {
document.getElementById("MediaFile").style.display = "inline-block";
document.getElementById("MediaLink").style.display = "none";
}
else {
document.getElementById("MediaFile").style.display = "none";
document.getElementById("MediaLink").style.display = "inline-block";
}
// })
}
Finally here is where I call the Partial view:
<div id="MediaList">
#for (i = 0; i < MediaCount; ++i)
{
<partial name="_MediaPartial" />
}
</div>
As #AlwaysHelping said in comment, Id selector MUST be unique for element. since you can not change their id, you can use name or class selector.
I made a demo based on your codes which change the id to name in partial. Also, I use jquery, it is much easier.
Partial view:
<div name="AddMedia">
<form>
<div class="container">
<div class="form-row">
<div class="col-6 dropdown my-2 px-0">
<label class="control-label">Source:<span class="text-danger ml-1">*</span></label>
<select name="SourceFromSelect" style="width:85%;" class="btn border-dark">
<option selected>Select</option>
<option value="1">Phone or Computer</option>
<option value="2">Other Media</option>
</select>
</div>
</div>
<div class="form-row">
<div class="col-5">
<div name="MediaFile" class="form-group">
<label for="exampleFormControlFile1">Pick a File</label>
<input type="file" class="form-control-file" name="exampleFormControlFile1">
</div>
<div name="MediaLink" class="form-group">
<label for="url">Link the Media</label>
<input type="url" class="form-control" name="exampleFormControlFile1">
</div>
</div>
</div>
</div>
</form>
</div>
Scripts:
<script>
$("[name = MediaFile]").css("display", "none")
$("[name = SourceFromSelect]").on('change', function () {
var parent = $(this.parentElement.parentElement.nextElementSibling)
if ($(this).find(":selected").text() == "Phone or Computer") {
parent.find("[name = MediaFile]").css("display", "inline-block");
parent.find("[name = MediaLink]").css("display", "none");
}
else {
parent.find("[name = MediaFile]").css("display", "none");
parent.find("[name = MediaLink]").css("display", "inline-block");
}
});
</script>
Result:

How to search for a user from a userslist using filter with ID value in AngularJS

I am working with a chat application. I need to put an input search box for the user to search for a friend from his friends list. I have written code to get ID values and and trigger it onkeyup. However, I am getting an uncaught reference error of function(name) is undefined. Here I am getting users list from server side using socket code.
Function in JS file
$scope.searchFn = function () {
var input, filter, ul, li;
input = document.getElementById("input");
// filter = input.value.toUpperCase();
ul = document.getElementById("list");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display =
"none";
}
}
}
HTML
<main>
<div class="container-fluid">
<input type="hidden" id="user" value="<%= user.username %>" />
<div class="row">
<div class="col-sm-4">
<div class="panel panel-success">
<div class="panel-heading">
<form action="/action_page.php" method="get">
<div class="input-group form-group">
<input id="input" class="form-control" name="browser" placeholder="Search friend.." ng-model="search" onkeypress="searchFn()">
<span class="input-group-btn">
<button class="btn btn-primary" type="button">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
<h4 align="center">Friends</h4>
</div>
<div class="panel-body" id="scrl1">
<ul id="list"></ul>
</div>
<div class="panel-footer">
<p id="typing"></p>
</div>
</div>
</div>
<div class=".space"></div>
<div class="col-sm-8">
<div class="panel panel-success">
<div class="panel-heading">
<h4 id="frndName" align="center">Chat Room</h4>
<a ng-click="clearchat()">
<span class="glyphicon glyphicon-trash" style="float:right;margin-top:-4%"></span>
</a>
</div>
<div class="panel-body" id="scrl2">
<p id="loading" align="center">Loading.....</p>
<p id="noChat" align="center">No More Chats To Display.....</p>
<p id="initMsg">!!...Click On User Or Group Button To Start Chat...!!</p>
<ul id="messages"></ul>
</div>
<div class="panel-footer input-group" style="width:100%">
<form id="chatForm" action="" onsubmit="return false">
<input id="myMsg" class="input-box-send form-control" ng-model="message" autocomplete="off" style="width:80%" placeholder="Write Message Here.." />
<button type="submit" id="sendBtn" class=" btn btn-primary " ng-disabled="!message" name="btn"><span class="glyphicon glyphicon-send"></span></button>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
Don't use function expression $scope.searchFn = function () {}.
Function expressions in JavaScript are not hoisted.
Use named functions to avoid such cases
function searchFn() {...}
You are not using an angular directive for triggering the keypress event. The "onkeypress" is an html attribute so any function declared on $scope will not be accessible. You should use ng-keypress directive.
Before:
<input id="input" class="form-control" name="browser" placeholder="Search friend.." ng-model="search" onkeypress="searchFn()">
After:
<input id="input" class="form-control" name="browser" placeholder="Search friend.." ng-model="search" ng-keypress="searchFn()">

ng-click or ng-change don't save array

I have a new auction form. The user has to insert all the requested field , then by clicking on a button "Invite People" can invite other saved users or can invite people by e mail. The email part works fine. But the users part give me some problem.
The html part:
<div ng-show="showBid" class="panel panel-default" ng-controller="NewAuctionController">
<div class="panel-heading">Invite Members</div>
<div class="panel-body">
<ul class="list-group" ng-repeat="user in users">
<li class="col-md-4" id="userlist" ng-hide="user.name == profile">
<img ng-src="{{user.img}}" class="userImage">
<div class="username"> {{user.name}}</div>
<div class="userrole"> {{user.role}} </div>
<div class="usercompany">{{user.company}}</div>
<input type="checkbox" ng-model="user.isChecked" ng-click="insertinvited(user)">
</li>
</ul>
The above part i tried also with ng-change, but it's the same.
The insertinvited() is:
$scope.invitations=[];
$scope.insertinvited= function (user) {
if(user.isChecked) {
$scope.invitations.push(user.name);
} else {
var toDel = $scope.invitations.indexOf(user.name);
$scope.invitations.splice(toDel,1);
}
console.log($scope.invitations);
};
In the console this works, cause when i check the box the array is pushed correctly
But when i try to use that array here:
<div ng-show="showBid" class="panel panel-default" >
<div class="panel-heading">Members Selected:</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item" ng-repeat="invitation in invitations">
<div class="listmail"> {{invitation}}</div>
</li>
</ul>
</div>
</div>
The array seems to be empty, infact when i pass the array to the controller and i try to do a console.log the array is empty.
Anyone could me help?
Edited
This is all my html code:
<form ng-controller="NewAuctionController"
name="myform">
<div>
<div ng-hide="showBid">
<div ng-show="uploading" class="progress">
</div>
<label class="btn" style="background-color: #858892">
Browse
<input type="file" ng-disabled="uploading" file-model="file.upload" name="myfile" style="display: none;" onchange="angular.element(this).scope().photoChanged(this.files)">
</label>
<br>
<br>
<br>
<img class="mythumbnail" ng-src="{{ thumbnail.dataUrl || default }}">
<br>
<br>
<div ng-show="message">
<div ng-class="alert">{{ message }}</div>
</div>
<div class="form-group" id="productname">
<label for="exampleInputName1">Product Name</label>
<input type="text" class="form-control" id="exampleInputName1" placeholder="Enter Product" ng-model="productTitle" >
</div>
<br>
<div class="form-group">
<label for="exampleInputdescription1"> Description:</label>
<input type="text" class="form-control" id="exampleInputdescription1" placeholder="Enter Description" ng-model="productDescription" >
</div>
<div class="form-group">
<label> Expiration Date:</label><br>
<input type="date" class="form-control" name="expiration date" ng-model="endtime" ><br>
</div>
<div class="quantity">
<label>Quantity:</label><br>
<input type="number" name="quantity" ng-model="quantity" placeholder="u" class="form-control" ><br>
</div>
<div class="Warranty">
<label>Warranty (days):</label><br>
<input type="number" name="warranty" class="form-control" ng-model="warranty" placeholder="days" ><br>
</div>
<div class="form-group">
<label>Minimum Price:</label><br>
<input type="number" name="minimum price" id="min" ng-model="minPrice" placeholder="€" class="form-control" ><br>
</div>
<div class="form-group">
<label>Buy-Now Price:</label><br>
<input type="number" name="minimum price" id="min" ng-model="productbuynow" placeholder="€" class="form-control" ><br>
</div>
<div class="form-group">
<label>Location of the goods:</label><br>
<input type="text" name="location" id="country" ng-model="Country" placeholder="Country" class="form-control" ><br>
<input type="text" name="Town" id="town" ng-model="Town" placeholder="Town" class="form-control" ><br>
<input type="text" name="address" id="address" ng-model="Address" placeholder="Address" class="form-control" ><br>
<input type="text" name="Postal code" id="postalCode" ng-model="PostalCode" placeholder="Postal Code" class="form-control" ><br>
</div>
<div class="form-group">
<label>Terms of payment: </label><br>
<select ng-model="payment">
<option value="Letter of credit">Letter of credit</option>
<option value="Cash in advance">Cash in advance</option>
<option value="Confirmed Irrevocable Credit">Confirmed irrevocable Credit</option>
</select><br>
</div>
<div class="form-group">
<label>Terms of Delivery: </label><br>
<select ng-model="delivery">
<option value="Carriage Paid To">Carriage Paid To</option>
<option value="Free Carrier">Free Carrier</option>
<option value="Confirmed Irrevocable Credit">Ex Works</option>
</select><br>
</div>
<input class="savebutton" type="submit" value="Invite People" ng-click="clickToOpen5()"><br>
<div ng-show="showBid" class="panel panel-default" ng-controller="NewAuctionController">
<div class="panel-heading">Invite Members</div>
<div class="panel-body">
<ul class="list-group" ng-repeat="user in users">
<li class="col-md-4" id="userlist" ng-hide="user.name == profile">
<img ng-src="{{user.img}}" class="userImage">
<div class="username"> {{user.name}}</div>
<div class="userrole"> {{user.role}} </div>
<div class="usercompany">{{user.company}}</div>
<input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">
</li>
</ul>
</div>
<div class="panel-heading">Members Selected:</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item" ng-repeat="invitation in invitations">
<div class="listmail"> {{invitation}}</div>
</li>
</ul>
</div>
<div class= "insertmail" ng-show=" showBid ">
Or Insert E-mail:<br>
<input type="email" name="emailaddress" ng-model="emailaddress">
<div ng-show="showBid" class="panel panel-default" >
<div class="panel-heading">Mail Inserted:</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item" ng-repeat="mail in mails">
<div class="listmail"> {{mail}}</div>
</li>
</ul>
</div>
</div>
<button ng-show="showBid" class="savebutton" ng-click="saveauction(profile)">SAVE</button><br>
</div>
</form>
And this is all my controller:
angular.module('NewAuctionCtrl', ['ngDialog', 'fileModelDirective', 'uploadFileService']).controller('NewAuctionController', ['$scope','$http' ,'ngDialog','uploadFile', '$timeout' , function($scope, $http, ngDialog, uploadFile, $timeout){
$scope.file = {};
$scope.message = false;
$scope.alert = '';
$scope.photoChanged = function (files) {
if (files.length > 0 && files[0].name.match(/\.(png|jpeg|jpg|pdf)$/)) {
$scope.uploading = true;
var file = files[0];
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(e) {
$timeout(function() {
$scope.thumbnail = {};
$scope.thumbnail.dataUrl = e.target.result;
$scope.uploading = false;
$scope.message = false;
});
};
} else {
$scope.thumbnail = {};
$scope.message = false;
}
};
$http.get('/api/users').then(function(Users) {
$scope.users = Users.data;
});
$scope.mails = [];
$scope.emailaddress = '';
$scope.insertmail = function () {
$scope.mails.push($scope.emailaddress);
$scope.emailaddress = '';
};
$scope.invitations = [] ;
$scope.insertinvited= function (user) {
if(user.isChecked) {
$scope.invitations.push(user.name);
} else {
var toDel = $scope.invitations.indexOf(user.name);
$scope.invitations.splice(toDel,1);
}
console.log($scope.invitations);
};
$scope.saveauction = function (user) {
console.log($scope.invitations);
var array = {
param1: $scope.productTitle,
param2: $scope.productDescription,
param3: $scope.endtime,
param4: $scope.minPrice,
param5: $scope.productbuynow,
param6: user,
param7: $scope.quantity,
param8: $scope.warranty,
param9: $scope.Country,
param10: $scope.Town,
param11: $scope.Address,
param12: $scope.PostalCode,
param13: $scope.payment,
param14: $scope.delivery,
param15:$scope.invitations
};
$scope.uploading = true;
uploadFile.upload($scope.file).then(function (data) {
if (data.data.success) {
$scope.uploading = false;
$scope.alert = 'alert alert-success';
$scope.message = data.data.message;
$scope.file = {};
$http.post('/api/newauction', array)
.then(
function () {
swal(
'Good job!',
'New Auction is created',
'success'
)
});
$scope.sendmail();
}
else {
$scope.uploading = false;
$scope.message = data.data.message;
swal(
'Oops...!',
$scope.message,
'error'
);
$scope.file = {};
}
});
};
$scope.clickToOpen5 = function () {
$scope.showBid = !$scope.showBid;
};
$scope.sendmail = function (){
var address = $scope.mails;
console.log(address);
if(address[0]) {
$http.post('/api/sendmail/', {address: address}).then(function (err) {
if (err)
console.log(err);
});
}
};
});
You should change ng-click to ng-change
<input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">
And in del of you , i think it should
var todel =$scope.invitations.indexOf(user.name);
$scope.invitations.splice(toDel,1);
This can be the problem of scope inheritance in angular JS.
try to do following changes:
In controller save this to some parameter like:
var vm = this;
now use vm.invitations instead of $scope.invitations.
and in ng-repeat use:
ng-repeat="invitation in vm.invitations"
You are clearing the array with each click.
Remove this statement:
$scope.invitations = [];
and move it to controller's main body; then it should work(especially if you're using ng-change).
this is due to the prototypical inheritance in javascript.
using var vm= this inside controller and
renaming $scope.invitations to vm.invitations in controller and invitations in html to vm.invitations.
will resolve the issue

Angular custom calculator with multiple functions

I need some help with a test calculator.
I managed to make the Add functionality work, but i'm stuck on what i have to do next in order to add an extra functionality like Multiply work when the Calculate button is pressed.
Here is a JSFiddle Link, and i will also add most of the code.
I chose Angular, but a jQuery example would do fine also.
Examples of the calculator lifecycle might be:
JS
angular.module('myApp', [])
.controller('MyController', function ($scope) {
$scope.items = [];
$scope.addItem = function(){
$scope.items.push({
myOperation: $scope.selectedOperation,
myNumber: $scope.selectedNumber
});
$scope.selectedOperation = '';
$scope.selectedNumber = '';
};
$scope.AddToTotal = function(){
var total = 0;
for(var i=0; i<$scope.items.length; i++){
total += $scope.items[i].myNumber;
}
return total;
}
});
Html
<body ng-app="myApp">
<div ng-controller="MyController" class="container">
<div class="row">
<div class=".col-md-6 .col-md-offset-3">
<form role="form" class="form-inline">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<!--Select-->
<select ng-model="selectedOperation" class="form-control input-lg" id="operators">
<option value="Add">Add</option>
<option value="Multiply">Multiply</option>
<option value="Apply">Apply</option>
</select>
<!--Input-->
<input ng-model="selectedNumber" class="form-control input-lg" type="number" placeholder="enter a number" />
<!--AddStep-->
<button ng-click="addItem()" id="btnAdd" class="btn btn-default btn-lg">Add step</button>
<p>{{selectedOperation}} {{selectedNumber}} = {{ AddToTotal()}}</p>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<ol id="instructions" class="jumbotron" style="margin-top: 2em;">
<li ng-repeat="item in items">{{item.myOperation}} {{item.myNumber}}</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<button ng-click="getTotal()" id="btnCalculate" class="btn btn-primary btn-lg">
Calculate
</button>
<button id="btnReset" class="btn btn-danger btn-lg">Reset</button>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<h2>Result:
<span id="result" class="result">{{ AddToTotal() }}</span>
</h2>
</div>
</div>
</form>
</div>
</div>
</div>
Update your AddToTotal function with this:
$scope.AddToTotal = function() {
var total = 0;
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].myOperation === 'Add') {
total += $scope.items[i].myNumber;
} else if ($scope.items[i].myOperation === 'Divide') {
total /= $scope.items[i].myNumber;
} else if ($scope.items[i].myOperation === 'Subtract') {
total -= $scope.items[i].myNumber;
} else if ($scope.items[i].myOperation === 'Multiply') {
total *= $scope.items[i].myNumber;
}
}
return total;
}

iterating a list of fields with ng-repeat and generate more data to be sent to the controller via ng-click,

I need help approaching the problem better or guide me a bit, I'm new angular.
I must first iterate a list of headers of a .csv file that list I have to make a match of three predefined fields, the remaining headers I have to generate a ng-repeat for so for each record generating radiobuttons and inputs with information I serve to create a new object, but when I click on the button that sends through the data ng-click on the controller this undefined
//controller
app.controller('fileController', [
'$scope',
'$http',
'ngAuthSettings',
'$location',
'localStorageService',
'fileService', '$rootScope', function ($scope, $http, ngAuthSettings, $location, localStorageService, fileService, $rootScope) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
var headersMatch = [];
var _lista_de_Headers = [];
var _lista_de_tags = [];
var _lista_de_header_splice = [];
$scope.restantesTag = [];
$scope.displayed = false;
$scope.secondDisplay = false;
//this is ok, get data from api and the header of file uploaded
$scope.uploadFile = function () {
var file = $scope.recipient;
fileService.uploadFileToUrl(file).then(
function (results) {
_lista_de_Headers = results.data.Headers;
_lista_de_header_splice = angular.copy(results.data.Headers);
_lista_de_tags = results.data.Tags;
$scope.displayed = true;
$scope.listaDeHeaders = _lista_de_Headers;
},
function (error) {
var errors = [];
for (var key in error.data.modelState) {
for (var i = 0; i < error.data.modelState[key].length; i++) {
errors.push(error.data.modelState[key][i]);
}
}
$scope.message = "Falla n:" + errors.join(' ');
}
);
};
//iterates the received data and creates an object with three main fields match
$scope.headerPpal = function (item) {
angular.forEach(item, function (index, element) {
headersMatch.push({
'Header': { "numberColumn": index.numberColumn, "nameColumn": element },
'Match': index.nameColumn,
'isReplace': false,
'Rename': null
});
angular.forEach(_lista_de_header_splice, function (i, obj) {
if (i.nameColumn === index.nameColumn) {
_lista_de_header_splice.splice(obj, 1);
};
});
});
$scope.secondDisplay = true;
$scope.restantesTag = _lista_de_header_splice;
$scope.listaDeTags = _lista_de_tags;
$rootScope.headersMatch = headersMatch;
$rootScope.lista_de_header_splice = _lista_de_header_splice;
};
$scope.mivariable = function (item) {
//Here is undefined the item
};
}]);
in the view
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h4 class="page-header">Mantenedor de Archivos</h4>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
Subir archivo
</div>
<div class="panel-body">
<div class="col-lg-12">
<div class="upl form-group pull-left col-lg-10">
<label for="file-upload" class="custom-file-upload btn btn-block btn-info pull-right">
<i class="fa fa-cloud-upload"></i> Seleccione archivo...
</label>
<input id="file-upload" type="file" file-model="recipient" />
</div>
<div class="form-group pull-left col-lg-2">
<input type="button" class="btn btn-primary" ng-click="uploadFile()" value="Subir" />
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row" ng-show="displayed">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
Seleccione Campos principales:
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<div class="form-group col-lg-4 center-block">
<span>
Email
<select ng-model="header.Email" ng-options="item.nameColumn for item in listaDeHeaders">
<!--<option value="null">No aplica</option>-->
</select>
</span>
</div>
<div class="form-group col-lg-4 center-block">
<span>
Nombre
<select ng-model="header.Name" ng-options="item as item.nameColumn for item in listaDeHeaders">
<option value="dontHave">No aplica</option>
</select>
</span>
</div>
<div class="form-group col-lg-4 center-block">
<span>
Fecha Nacimiento
<select ng-model="header.BirthDate" ng-options="item as item.nameColumn for item in listaDeHeaders">
<option value="dontHave">no aplica</option>
</select>
</span>
</div>
</div>
<div class="form-group col-lg-12">
<button id="step1_next" class="btn btn-primary pull-right" ng-click="headerPpal(header)">
siguiente
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row" ng-show="secondDisplay">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
Agregue configuracion de Tags:
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<div ng-repeat="tag in restantesTag">
<div>
<input type="text" data-ng-model="tag.nameColumn" class="form-control success" placeholder="{{tag.nameColumn}}" value="{{tag.nameColumn}}" disabled>
<input type="text" data-ng-model="tag.numberColumn" value="{{tag.numberColumn}}" hidden>
</div>
<div>
<input type="radio" data-ng-model="tag.isReplace" value="true" />Agregar<br />
<input type="radio" data-ng-model="tag.isReplace" value="false" />Reemplazar
</div>
<div>
<span>
<select data-ng-model="tag.Header" ng-options="x for x in listaDeTags">
<option value="">No aplica</option>
</select>
</span>
</div>
<div><input type="text" data-ng-model="tag.Value" class="form-control"></div>
</div>
<div class="form-group col-lg-12">
<button type="submit" class="btn btn-primary pull-right" ng-click="mivariable(tag)">
Guardar
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Thank you so much for everything !!

Categories