Backbonejs: get clicked model from collection - backbone.js

define(['jquery', 'underscore', 'backbone', 'text!views/manageUsers.tpl', 'common'], function($, _, Backbone, tmpl_manageUsersView, ajax) {
/*
* Module list
*
* tmpl_page1View templates/tmpl_page1View.html
*/
var manageUsersView = Backbone.View.extend({
// Setting the view's template property using the Underscore template method
template: _.template(tmpl_manageUsersView),
// View constructor
initialize: function() {
self = this;
},
// View Event Handlers
events: {
},
// Renders the view's template to the UI
render: function() {
this.$el.html(this.template({data: this.templateData}));
user=Backbone.Model.extend({
defaults:{
name:"",
password:"",
isAdmin:false
},
});
users=Backbone.Collection.extend({
model:user,
url:"auth"
});
usersCollection=new users();
usersCollection.fetch({
error:function(response,xhr){
console.log(response);
},
success:function(response){
count=1;
_.each(data,function(d){
if(count%2==0)
$("#users>tbody").append("<tr class='odd'><td>"+count+"</td><td>"+d.username+"</td><td><a href='#' class='edit-iocn' id='edit_"+d.username+"' ></a><a class='ancrul delete-icon' id='delete_"+d.username+"'></a></td>");
else
$("#users>tbody").append("<tr class='even'><td>"+count+"</td><td>"+d.username+"</td><td><a href='#' class='edit-iocn' id='edit_"+d.username+"'></a><a class='ancrul delete-icon' id='delete_"+d.username+"'></a></td>");
count++;
});
/*--*/
var oTable = $('#users').dataTable({
"sDom": '<"bottom"<i>rtp<"clear">',
//"sDom":'<"top"ip>rt<"bottom"ip<"clear">',
"sPaginationType": "full_numbers",
"bLengthChange": true,
"bPaginate": true,
"bInfo": true,
//"bAutoWidth": true,
"iDisplayLength":5,
"oLanguage": {
"sInfo": "",
"sInfoEmpty": ""
},
});
}
});
});
return manageUsersView;
});
Above is my code for getting data from url.
Following manageUsers.tpl file.
<div class="content">
<p> </p>
<h3></h3>
<div class="admin-login-area ui-corner-all">
<p class="validateTips">All form fields are required.</p>
<form id="addUserForm">
<fieldset>
<label for="name" class="login-label">User Name</label>
<input type="text" name="u-name" id="u-name" class="text ui-widget-content ui-corner-all">
<label for="name" class="login-label">Password</label>
<input type="password" name="p-name" id="p-name" class="text ui-widget-content ui-corner-all">
<label for="email" class="login-label">Retype Password</label>
<input type="password" class="text ui-widget-content ui-corner-all" id="c-name" name="c-name">
<input type="checkbox" id="isAdmin" />
<label>Is Admin</label>
<label class="login-label"></label>
<br/>
<input type="button" name="submit" id="submit" value="Submit" class="submit-btn">
<input type="button" name="submit" id="reset" value="Reset" class="submit-btn">
<input type="button" name="submit" id="cancel" value="Cancel" class="submit-btn">
<label class="login-label"></label>
</fieldset>
</form>
<!-- end admin login --></div>
<div class="table" >
<table width="100%" cellspacing="0" cellpadding="0" border="0" id="users">
<thead>
<th>Sr No</th>
<th>users</th>
<th>Actions</th>
</thead>
<tfoot style="display: table-header-group;">
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</div>
and on fetching data successfully i have filled table with collectios's data and on click of an item in table i want to retrive whole model.I have form and table in same tpl file
How to do that using backbonejs and underscore js?

First, add this event to your view :
events : {
'click .edit-iocn' : 'edit', // in your code you typed `iocn` instead of `icon`
'click .delete-icon' : 'delete'
}
Than change the ids to id='"+d.username+"' without the edit_ and delete_
And last the edit and delete methods :
edit: function(event) {
var username = event.currentTarget.id;
var user = usersCollection.where({name: username})[0];
...
}
delete: function(event) {
var username = event.currentTarget.id;
var user = usersCollection.where({name: username})[0];
...
}

Related

Not able to display the time format data from the firebase database connected to my Angular app

Am trying to display the time format data from the firebase database, that I have connected to the angular app, the html tag with the input type"text" is displaying fine on the dashboard but there is the problem with the time format and it is not getting displayed.
Here is the below HTML code
<div class = "row" ng-controller = "taskCtrl" >
<div class = "col-md-5">
<h3> Add Task </h3>
<form ng-submit= "addtask()">
<div class="form-group">
<select ng-model="selectedName" ng-options="X as X.Appname for X in appy">
</select>
</div>
<div class="form-group">
<label >Task Name</label>
<input type="text" class="form-control" ng-model = "tname" placeholder="Task Name">
</div>
<div class="form-group">
<label >Task Description</label>
<input type="text" class="form-control" ng-model = "tdes" placeholder="Task Description">
</div>
<div class="form-group">
<label >Task start time </label>
<input type= "text" class="form-control" ng-model = "tstime" placeholder="Task start time" >
</div>
<div class="form-group">
<label >Task Info</label>
<input type="time" class="form-control" ng-model = "tetime" placeholder="Task end time">
</div>
<div class="form-group">
<label >Phone number</label>
<input type="text" class="form-control" ng-model = "phno" placeholder="Phone number">
</div>
<button type = "submit" class = "btn btn-default">Submit</button>
</form>
</div>
<div class = "col-md-7">
<h3> Contacts</h3>
<table class= "table table-striped">
<thead>
<tr>
<th>Task Name </th>
<th>Task Description</th>
<th>Task Start time </th>
<th>Task End Time </th>
<th> Task Status </th>
</tr>
<tbody>
<tr ng-repeat = "tas in task">
<td> {{tas.tname}}</td>
<td> {{tas.tdes}}</td>
<td> {{tas.tstime}}</td>
<td> {{tas.tetime}}</td>
</tr>
</tbody>
</thead>
</table>
</div>
</div>
Here is the below javascript code :
'use strict';
angular.module('myApp.task', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/task', {
templateUrl: 'views/task.html',
controller: 'taskCtrl'
});
}])
.controller('taskCtrl', ['$scope','$firebaseArray',function($scope, $firebaseArray) {
var ref = new Firebase('https://contactlist9934.firebaseio.com/task');
$scope.task = $firebaseArray(ref);
var ref3 = new Firebase('https://contactlist9934.firebaseio.com/application');
$scope.appy = $firebaseArray(ref3);
$scope.addtask = function(){
var r1;
var r2;
var r3;
var r4;
r1 = $scope.tstime.toString();
r2 = r1.substring(16,24);
r3 = $scope.tetime.toString();
r4 = r3.substring(16,24);
$scope.task.$add({
tname: $scope.tname,
tdes: $scope.tdes,
etime: r2,
ttime: r4,
appname: $scope.selectedName.Appname
}).then(function(ref){
var id = ref.key();
console.log('Added Task' +id);
$scope.name = '';
$scope.email = '';
});
}
}])
.controller('myCtrl', function($scope) {
});
The text fields are getting displayed fine but the time format is not getting diaplayed, help me out on this one !!
You could use a filter for this and convert the tstime and tetime in your controller to your desired format like this:
$scope.tstime = $filter('date')($scope.tstime, 'yyyy/MM/dd');
$scope.tetime = $filter('date')($scope.tetime, 'yyyy/MM/dd');
Or if you want to use a directive and use it in multiple inputs you can make a directive something like this:
.directive('formatDate', ['$timeout', '$filter', function ($timeout, $filter) {
return {
require: 'ngModel',
link: function ($scope, $element, $attrs, $ctrl) {
var dateFormat = 'yyyy/MM/dd';
$ctrl.$parsers.push(function (viewValue) {
var pDate = Date.parse(viewValue);
if (isNaN(pDate) === false) {
return new Date(pDate);
}
return undefined;
});
$ctrl.$formatters.push(function (modelValue) {
var pDate = Date.parse(modelValue);
if (isNaN(pDate) === false) {
return $filter('date')(new Date(pDate), dateFormat);
}
return undefined;
});
$element.on('blur', function () {
var pDate = Date.parse($ctrl.$modelValue);
if (isNaN(pDate) === true) {
$ctrl.$setViewValue(null);
$ctrl.$render();
} else {
if ($element.val() !== $filter('date')(new Date(pDate), dateFormat)) {
$ctrl.$setViewValue($filter('date')(new Date(pDate), dateFormat));
$ctrl.$render();
}
}
});
}
};
}]);
And bind it to your input like this:
<input type= "text" class="form-control" format-date ng-model="tstime" placeholder="Task start time">
<input type="time" class="form-control" format-date ng-model="tetime" placeholder="Task end time">
This is fixed now, as I was trying to fetch the data from the firebase, the below variables should match in the below codes :- -
HTML
<tr ng-repeat = "tas in taski">
<td> {{tas.tname}}</td>
<td> {{tas.tdes}} </td>
<td> {{tas.etime}}</td>
<td> {{tas.ttime}}</td>
<td> {{tas.appname}}</td>
</tr>
Script
$scope.task.$add({
tname: $scope.tname,
tdes: $scope.tdes,
etime: $scope.tstime,
ttime: r4,
appname: $scope.selectedName.Appname
}).then(function(ref)

Adding data to table dynamically:data updated is not getting reflected only the row get added

<html ng-controller='myctrl'>
<head>Student creation</head>
<table border=1 width="100%">
<tr style=background-color:lightblue>
<th>username</th>
<th>password</th>
<th>department</th>
<th>action</th>
</tr>
<tr ng-repeat=" student in students" >
<td>{{student.username}}</td>
<td>{{student.password}}</td>
<td>{{student.department}}</td>
<td style=text-align:center>
Edit&nbsp
<a onclick="calldeletefun()">delete</a>
<script>
function calldeletefun() {
if (confirm("Do you want to delete student <<student name>>?") == true) {
x = "you pressed ok";
} else
x = "you pressed cancel";
document.getElementById("demo").innerHTML = x;
}
</script>
&nbspmarks
</td>
</tr>
</table>
<p id="demo"></p>
<head>Student Edit/Add</head>
<br><br>
<body style=text-align:center>
<form role="form" ng-submit="addRow()">
<div>Studentname:
<input type="text" name="username" ng-model="username" style=border-color:blue ><br><br></div>
<div>Password:&nbsp&nbsp&nbsp
<input type="password" name="password" ng-model="password" style=border-color:blue><br><br></div>
<div>Department:
<input type="text1" name="department" ng-model="department" style=border-color:blue><br><br></div>
<div><input type="submit" value="submit" style="color:white; background-color:green" >
<input type ="submit" style="background-color:red; color:white" value="cancel"></div>
</form>
</body>
</html>
Adding data to table dynamically:
On submitting the form only new row get added but data's given is not getting updated,Following is my controller code
var app = angular.module('myapp', ['ngRoute'])
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'table.html'
})
.when('/table1',
{
templateUrl : 'table.html'
})
.otherwise({
redirectTo : '/'
});
});
app.controller('myctrl', function ($scope) {
$scope.students = [{
'username' : 'user1',
'password' : 'user1',
'department' : 'cse'
}, {
'username' : 'user2',
'password' : 'user2',
'department' : 'IT'
}, ];
$scope.addRow = function () {
$scope.students.push({
username : $scope.username,
'password' : $scope.password,
'department' : $scope.department
});
$scope.username = "";
$scope.password = "";
$scope.department = "";
};
});
What went wrong here ? Can any please debug the code.
put ng-app in your HTML tag like
<html ng-app='myapp' ng-controller='myctrl'>
Remove ng-submit from form tag and put ng-click ="addRow()" on button.
Put return false in addRow function of your controller.
Let me know if this works for you.
The row is not getting added to the table because of the form is getting submitted i.e page is refreshing..
See the working snippet I have added; the problem is with your html.
Maybe this will help you:
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
$scope.students=[{'username':'user1','password':'user1','department':'cse'},
{'username':'user2','password':'user2','department':'IT'},];
$scope.addRow=function()
{
$scope.students.push({username:$scope.username,'password':$scope.password,'department':$scope.department});
$scope.username="";
$scope.password="";
$scope.department="";
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="1" data-ng-app="myApp" data-ng-controller="myctrl">
<table border=1 width="100%">
<tr style=background-color:lightblue>
<th>username</th>
<th>password</th>
<th>department</th>
<th>action</th>
</tr>
<tr ng-repeat=" student in students" >
<td>{{student.username}}</td>
<td>{{student.password}}</td>
<td>{{student.department}}</td>
<td style=text-align:center>
Edit&nbsp
<a onclick="calldeletefun()">delete</a>
<script>
function calldeletefun()
{
if(confirm("Do you want to delete student <<student name>>?")==true)
{
x="you pressed ok";
}
else
x="you pressed cancel";
document.getElementById("demo").innerHTML=x;
}
</script>
&nbspmarks
</td>
</tr>
</table>
<p id="demo"></p>
<h3>Student Edit/Add</h3>
<form role="form" ng-submit="addRow()">
<div>Studentname:
<input type="text" name="username" ng-model="username" style=border-color:blue ><br><br></div>
<div>Password:&nbsp&nbsp&nbsp
<input type="password" name="password" ng-model="password" style=border-color:blue><br><br></div>
<div>Department:
<input type="text1" name="department" ng-model="department" style=border-color:blue><br><br></div>
<div><input type="submit" value="submit" style="color:white; background-color:green" >
<input type ="submit" style="background-color:red; color:white" value="cancel"></div>
</form>
</div>

submit button not working for AngularJS

I am new to angularJS as well as MVC. Just tried a simple CRUD operation .
The GetallEmployee() and the edit operation call are working fine. However the submit is not working. I am sure there is a lot of blunder in the code .Apologies for that .
Here is my Controller and service and view that I added....
app.controller("myController", ['$scope', '$http', 'angularService', function ($scope, $http, angularService) {
$scope.employees = [];
var fetched = angularService.GetAllEmployee();
fetched.then(function (emps) {
$scope.employees = emps.data;
});
$scope.editEmployee = function (data) {
var Emp = $http({
method: "get",
url: "Home/GetEmployeebyId",
params: {
Id: JSON.stringify(data.ID)
}
}).success(function (Emp) {
$scope.employeeName = Emp.Name;
$scope.employeeId = Emp.ID;
$scope.employeeEmail = Emp.Email;
$scope.employeeAge = Emp.Age;
$scope.Action = "Update";
$scope.IsIndian = Boolean(Emp.IsIndian);
$scope.employeeGender = Emp.Gender;
});
};
$scope.AddUpdateEmployee = function () {
var Employee = {
Id: $scope.employeeId,
Name: $scope.employeeName,
Email: $scope.employeeEmail,
Age: $scope.employeeAge,
Gender: $scope.employeeGender,
IsIndian: $scope.IsIndian,
};
var getAction = $scope.Action;
if (getAction == 'Update') {
Employee.Id = $scope.employeeId;
$http({ method: 'post', url: 'Home/UpdateEmployee', data: JSON.stringify(Employee), datatype: 'json' }).success
(function (output) {
var fetched = angularService.GetAllEmployee();
fetched.then(function (emps)
{
$scope.employees = emps.data;
}
)
ClearFields();
});
}
else {
$http({ method: 'post', url: 'Home/AddEmployee', data: JSON.stringify(Employee), datatype: 'json' }).success
(function () {
var fetched = angularService.GetAllEmployee();
fetched.then(function (emps) {
$scope.employees = emps.data;
alert(output);
ClearFields();
});
}
);
}
$scope.Action = "";
}
////$scope.deleteEmployee = function (employee) {
//// angularService.deleteEmployee(employee.ID).then(function (msg) {
//// GetAllEmployee();
//// alert(msg.data);/////earlier it was a string message in place if msg.data
//// }, function () {
//// alert('Error in Deleting Record');
//// });
////}
function ClearFields() {
$scope.employeeId = "";
$scope.employeeName = "";
$scope.employeeEmail = "";
$scope.employeeAge = "";
$scope.IsIndian = false;
$scope.Gender = 'Male';
}
}]);
app.service("angularService", function ($http) {
//get All Eployee
var temp = this;
temp.employee = [];
this.GetAllEmployee = function () {
return $http.get("Home/GetAll").success(function (emps) {
emps.forEach(function (eachemp) {
eachemp.IsIndian = Boolean(eachemp.IsIndian);
temp.employee.push(eachemp);
})
});
}
});
#{
ViewBag.Title = "Home Page";
}
<div ng-controller="myController as myController" ng-app="MyApp">
<br />
<div>
<table class="table ">
<tr>
<td colspan="6" align="center">
<label style="font-family:Arial ;font-weight:bold">Employee Details</label>
</td>
</tr>
<tr>
<td style="font-weight:bold">Name</td>
<td style="font-weight:bold">Id</td>
<td style="font-weight:bold">Email</td>
<td style="font-weight:bold">Age</td>
<td style="font-weight:bold"></td>
</tr>
<tr ng-repeat="emp in employees">
<td>{{emp.Name}}</td>
<td>{{emp.ID}}</td>
<td>{{emp.Email}}</td>
<td>{{emp.Age}}</td>
<td>
<button ng-click="editEmployee(emp)" type="submit" class="btn btn-primary">Edit</button>
<button ng-click="deleteEmployee(emp)" type="submit" class="btn btn-primary">Delete</button>
</td>
<td>
<input type="checkbox" ng-model="emp.IsIndian" disabled="disabled" name="IndianChk" /> Indian
<input type="radio" disabled="disabled" ng-model="emp.Gender" value="Male"> Male
<input type="radio" disabled="disabled" ng-model="emp.Gender" value="Female" />Female
</td>
</tr>
</table>
</div>
<form name="form" ng-submit="myController.addupdateemployee()">
<table class="table table-responsive">
<tr>
<td>
<label>Employee ID </label>
</td>
<td>
<input type="text" disabled="disabled" ng-model="employeeId" class="form-control" />
</td>
</tr>
<tr>
<td>
<label>Employee Name </label>
</td>
<td>
<div class="form-group" ng-class="{'has-error': form.empname.$invalid && form.empname.$dirty }">
<input type="text" ng-model="employeeName" class="form-control" required name="empname" />
</div>
</td>
</tr>
<tr>
<td>
<label>Employee Email </label>
</td>
<td>
<div class="form-group" ng-class="{'has-error': form.mail.$invalid && form.mail.$dirty }">
<input type="text" ng-model="employeeEmail" class="form-control" required name="mail" />
</div>
</td>
</tr>
<tr>
<td>
<label>Gender</label>
</td>
<td>
<div>
<select class="form-control" ng-model="employeeGender" required>
<option>Male</option>
<option>Female</option>
</select>
</div>
</td>
</tr>
<tr>
<td>
<label>Employee Age </label>
</td>
<td>
<div class="form-group">
<input type="number" ng-model="employeeAge" required class="form-control" name="age">
</div>
</td>
</tr>
<tr>
<td>
<label>Is Indian </label> <input type="checkbox" ng-model="IsIndian" ng-required="true" />
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="submit">submit</button>
</td>
</tr>
</table>
</form>
</div>
Change your form tag from:
<form name="form" ng-submit="myController.addupdateemployee()">
to
<form ng-submit="AddUpdateEmployee()" ng-controller="myController">

how to establish a two-way binding between a text input and a parent scope model

In my Angular app, I have a view, which is presented as a tabbed UI, with multiple tabs created by default.
Each tab contains a number of Form elements, one of which is a text input named "tabName".
The purpose of each tab is to allow the user to upload an Excel file, and be able to describe the file contents using a few Form fields located on the same page.
All of the form elements in each tab are bound to a controller named "FileUploadController", but, the tab itself (specifically its name) is bound to a different controller, named "TabController".
I need to be able to have a two-way binding between the "tabName" text input in each tab, and the name property of the actual tab (which initially comes from "$scope.workspaces" within the TabController.
Currently, I am trying to handle this by creating a "activeWorkspaceSheetName" function within the TabController, and then referencing it as ng-model for the text input, but, it is not working.
Here are my files:
tabControl.html (the view):
<div class="container form-group">
<br>
<tabset>
<tab ng-repeat="workspace in workspaces"
heading="{{workspace.name}}"
active=workspace.active>
<div ng-controller="FileUploadController">
<hr>
<!--FILE UPLOAD CONTROL-->
<div class="container">
<div class="row">
<div class="col-md-3">
<input type="file" nv-file-select="" uploader="uploader" />
</div>
<div class="col-md-9" style="margin-bottom: 40px">
<h3>Upload queue</h3>
<p>Queue length: {{ uploader.queue.length }}</p>
<table class="table">
<thead>
<tr>
<th width="50%">Name</th>
<th ng-show="uploader.isHTML5">Size</th>
<th ng-show="uploader.isHTML5">Progress</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in uploader.queue">
<td><strong>{{ item.file.name }}</strong></td>
<td ng-show="uploader.isHTML5" nowrap>{{ item.file.size/1024/1024|number:2 }} MB</td>
<td ng-show="uploader.isHTML5">
<div class="progress" style="margin-bottom: 0;">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': item.progress + '%' }"></div>
</div>
</td>
<td class="text-center">
<span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
<span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
<span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
</td>
<td nowrap>
<button type="button" class="btn btn-success btn-xs" ng-click="item.upload()" ng-disabled="item.isReady || item.isUploading || item.isSuccess">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
<button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()" ng-disabled="!item.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel
</button>
<button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">
<span class="glyphicon glyphicon-trash"></span> Remove
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!--END OF FILE UPLOAD CONTROL-->
<div class="form-group">
<fieldset>
<legend><strong>Dataset Description</strong> </legend>
<div class="col-sm-6">
<label for="category">Category name</label>
<div id="category">
<isteven-multi-select
input-model="inputCategories"
output-model="outputCategories"
button-label="icon name"
item-label="icon name maker"
tick-property="ticked"
selection-mode="single"
>
</isteven-multi-select>
</div>
<label for="documentAuthor">Document author</label>
<input id="documentAuthor" name="documentAuthor" type="text" class="form-control" ng-model="documentAuthor"/>
<label for="dateDocumentRecieved">Date document recieved</label>
<input id="dateDocumentRecieved" name="dateDocumentRecieved" type="text" class="form-control" ng-model="dateDocumentReceived"/>
<label for="documentReviewer">Document reviewer</label>
<input id="documentReviewer" name="documentReviewer" type="text" class="form-control" ng-model="documentReviewer"/>
</div>
<div class="col-sm-6">
<label for="originalDocumentName">Original document name</label>
<input id="originalDocumentName" name="originalDocumentName" type="text" class="form-control" ng-model="originalDocumentName"/>
<label for="tabName">Sheet Name</label>
<input id="tabName" name="tabName" type="text" class="form-control" ng-model="$scope.$parent.activeWorkspaceSheetName"/>
<label for="dateDocumentProduced">Date document produced</label>
<input id="dateDocumentProduced" name="dateDocumentProduced" type="text" class="form-control" ng-model="dateDocumentProduced"/>
<label for="documentSubmitter">Document submitter</label>
<input id="documentSubmitter" name="documentSubmitter" type="text" class="form-control" ng-model="documentSubmitter"/>
</div>
</fieldset>
</div>
</div>
</tab>
<tab select="addWorkspace()">
<tab-heading> Add Sheet
<i class="icon-plus-sign"></i>
</tab-heading>
</tab>
<tab select="removeWorkspace()">
<tab-heading> Remove Selected Sheet
<i class="icon-plus-sign"></i>
</tab-heading>
</tab>
</tabset>
<br/>
<!--<button type="button" class="btn-primary" ng-click="collectValuesFromEachTab()">Submit Dataset</button>-->
<!--<h3>Workspaces</h3>-->
<!--<pre>{{workspaces|json}}</pre>-->
</div>
tabController.js:
angular.module('TabCtrl', ['ui.bootstrap'])
.controller("TabController", ['$scope','$http', function ($scope, $http) {
console.log("This is TabController");
var setAllInactive = function() {
angular.forEach($scope.workspaces, function(workspace) {
workspace.active = false;
});
};
$scope.activeWorkspaceSheetName = function(){
$scope.workspaces.forEach(function(workspace) {
if(workspace.active){
return workspace.name;
}
});
};
var addNewWorkspace = function() {
var id = $scope.workspaces.length + 1;
$scope.workspaces.push({
id: id,
name: "Sheet " + id,
active: true
});
};
$scope.workspaces =
[
{ id: 1, name: "Sheet 1" ,active:true },
{ id: 2, name: "Sheet 2" ,active:false }
];
$scope.addWorkspace = function () {
setAllInactive();
addNewWorkspace();
};
$scope.removeWorkspace = function() {
angular.forEach($scope.workspaces, function(workspace) {
if(workspace.active){
var index = $scope.workspaces.indexOf(workspace);
console.log('Active Workspace id: ' + index);
$scope.workspaces.splice(index,1);
}
})
};
}]);
fileUploadController.js:
angular.module('FileUploadCtrl', [])
.controller('FileUploadController', ['$scope', 'FileUploader', function($scope, FileUploader) {
console.log('This is File Upload Controller');
$scope.inputCategories = [
{
name: "Category 1"
},
{
name: "Category 2"
},
{
name: "Category 3"
}
];
var selectedCategory;
var uploader = $scope.uploader = new FileUploader({
url: 'http://10.211.55.25:8080/api/files',
tabName: 'sheet1'
});
// FILTERS
uploader.filters.push({
name: 'customFilter',
fn: function(item /*{File|FileLikeObject}*/, options) {
return this.queue.length < 10;
}
});
// CALLBACKS
uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
console.info('onWhenAddingFileFailed', item, filter, options);
};
uploader.onAfterAddingFile = function(fileItem) {
console.info('onAfterAddingFile', fileItem);
};
uploader.onAfterAddingAll = function(addedFileItems) {
console.info('onAfterAddingAll', addedFileItems);
};
uploader.onBeforeUploadItem = function(item) {
angular.forEach( $scope.outputCategories, function( value, key ) {
selectedCategory = value.name;
item.formData.push({subjectCategory: selectedCategory});
});
$scope.tabName = $scope.$parent.activeWorkspaceSheetName;
item.formData.push({tabName: $scope.tabName,
originalDocumentName: $scope.originalDocumentName,
subject: $scope.subject,
documentAuthor: $scope.documentAuthor,
dateDocumentProduced: $scope.dateDocumentProduced,
dateDocumentReceived: $scope.dateDocumentReceived,
documentSubmitter: $scope.documentSubmitter,
documentReviewer: $scope.documentReviewer,
dataFields: $scope.dataFields});
console.info('onBeforeUploadItem', item);
};
uploader.onProgressItem = function(fileItem, progress) {
console.info('onProgressItem', fileItem, progress);
};
uploader.onProgressAll = function(progress) {
console.info('onProgressAll', progress);
};
uploader.onSuccessItem = function(fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
};
uploader.onErrorItem = function(fileItem, response, status, headers) {
console.info('onErrorItem', fileItem, response, status, headers);
};
uploader.onCancelItem = function(fileItem, response, status, headers) {
console.info('onCancelItem', fileItem, response, status, headers);
};
uploader.onCompleteItem = function(fileItem, response, status, headers) {
console.info('onCompleteItem', fileItem, response, status, headers);
};
uploader.onCompleteAll = function() {
console.info('onCompleteAll');
};
console.info('uploader', uploader);
}]);
What is the proper way to have this two-way binding, so, when the user updates the tabName text input in each tab, the actual tab's name is also updated?
If I understood correctly you has an input tabName for each tab so you can try put this model in the tabName input:
<input id="tabName" name="tabName" type="text" class="form-control" ng-model="workspace.name"/>
Remember every time that angular can't find a property in a scope they look if exist in his parent, and if not exist they check in his parent parent and so on...

Form validation Not working with angularJS

I've a form inside table.
<table class='table table-bordered'>
<caption>ADD NEW BRAND</caption>
<tbody>
<form ng-app="" class="form-horizontal" role="form" name="myForm">
<div class="form-group">
<TR>
<TD>Brand Name</TD>
<TD>
<input type="text" class="form-control" name="name" ng-model="newbrand.Name" placeholder="Enter Brand Name" required>
<span style="color:red" ng-show="myForm.name.$dirty && myForm.name.$invalid">
<span ng-show="myForm.name.$error.required">Brand Name is required.</span>
</span>
</TD>
</TR>
</div>
</form>
</tbody>
</table>
When input field is empty, it should give a indication that Brand Name is required. But its not working.
Can someone please help me on this.
You can do that using directive:-
For an example:
html
<body ng-controller="MainCtrl">
<form novalidate class="person" name="personForm" test-directive validation="submitPerson" ng-submit="submitForm(personForm)">
<h3>Person form</h3>
<input type="text" required name="first-name" ng-model="person.firstName" ng-class="{'valid':personValid}" />
<input type="submit" value="post" />
</form>
</body>
Controller & Directive
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.person = {
firstName: 'Clem'
};
$scope.submitPerson = function(form, element) {
console.log("Person validation here!")
if(form.$valid) {
$scope.personValid = true;
}
else {
$scope.personValid = false;
}
};
});
app.directive('testDirective', function ($compile) {
return {
restrict: 'A',
scope: true,
link: function (scope, ele, attrs) {
scope.submitForm = function(form) {
eval("var fn = scope." + attrs.validation);
fn(form, ele);
}
}
};
})
Credit :- Form validation in angular

Resources