AngularJS- some of my scope variables not displaying - javascript

I'm a new developer using Angular JS to create an orders page for an app I created in Ruby on Rails. I would like to get a few Angular variables to display:
order.id (displays)
order.user.email (does not display)
order.total (does not display)
order.product.name (displays)
Only 2 of the 4 variables display. When I put a string or integer into the {{}} Angular notation in place of order.total | currency, the string or integer displays. However, when I try the same with order.product.name, nothing happens.
Here is my relevant code:
View.html:
<div ng-controller="OrdersCtrl">
<h1>Orders</h1>
<div class="container">
<form class="form-inline" ng-submit="addOrder()">
<strong>Add Order: </strong>
<select ng-model="newOrder.product_id" class="form-control">
<option value="" disabled selected>Select a Product</option>
<option ng-repeat="product in products" value="{{product.id}}"> {{product.name}}</option>
</select>
<input type="number" step="1" class="form-control" placeholder="Total" ng-model="newOrder.total">
<input type="number" class="form-control" ng-model="newOrder.product_id">
<input type="submit" value="+" class="btn btn-success">
</form>
<table class="table table-hover">
<thead>
<td>Order ID</td>
<td>Total</td>
<td>Product</td>
<td></td>
</thead>
<tr ng-repeat="order in orders | orderBy:'-id':reverse">
<td>
{{order.id}}<small ng-show="order.user_id"><br>-{{order.user.email}}</small>
</td>
<td>
<strong>{{order.total | currency}}</strong>
</td>
<td>
{{order.product.name}}
</td>
<td>
<button ng-click="deleteOrder(order)" class="btn btn-danger btn-sm"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>
</td>
</tr>
</table>
</div>
Controller (app.js)
var app = angular.module('shop', ['ngResource']);
//Workaround to get Angular running
$(document).on('ready page:load', function() {
angular.bootstrap(document.body, ['shop'])
});
//factory for models
app.factory('models', ['$resource', function($resource){
var orders_model = $resource("/orders/:id.json", {id: "#id"});
var products_model = $resource("/products/:id.json", {id: "#id"});
var x = {
orders: orders_model,
products: products_model
};
return x;
}]);
//connect app to OrdersCtrl controller
app.controller('OrdersCtrl', ['$scope', 'models', function($scope, models){
// Here will be all code belonging to this controller
$scope.orders = models.orders.query();
$scope.products = models.products.query();
//add new orders
$scope.addOrder = function(){
//only orders with product id or zero total gets added
if(!$scope.newOrder.product_id || $scope.newOrder.total === ''){ return; }
//Order can be submitted if product_id and total are filled out
order = models.orders.save($scope.newOrder, function(){ //POST
recent_order = models.orders.get({id: order.id});
$scope.orders.push(recent_order);
$scope.newOrder = '';
});
}
//delete orders
$scope.deleteOrder = function(order){
models.orders.delete(order);
$scope.orders.splice($scope.orders.indexOf(order), 1);
};
}]);

Related

How to get Array data wihile ng-change function in ng repeat for every iteration

var app = angular.module("myapp", []);
app.controller("ctrl", function($scope, $http, jsonFilter) {
$scope.loadcat = function() {
$http.get("cat_load.php")
.success(function(data, status, headers, config) {
$scope.CategoryArray = data;
});
}
$scope.GetProduct = function(categoryid, index) {
$http.post("product_load.php", {
'cat_id': categoryid
})
.success(function(data, status, headers, config) {
$scope.ProductsArray[index] = data;
});
}
$scope.GetSubCategory = function(categoryid, productname) {
$http.post("subcat_load.php", {
'cat_id': categoryid,
'productname': productname
})
.success(function(data, status, headers, config) {
$scope.subcatids = data;
});
}
/**********to add remove row start here **********/
$scope.remove_Row = function(name) {
var index = -1;
var comArr = eval($scope.data);
for (var i = 0; i < comArr.length; i++) {
if (comArr[i].name == name) {
index = i;
break;
}
}
if (index == -1) {
//alert( "Something gone wrong" );
}
$scope.data.splice(index, 1);
};
// dynamic row creation
$scope.data = [{}];
$scope.addFormField = function() {
//alert($scope.data);
$scope.data.push({});
}
/**********to add remove row End here **********/
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body class="no-skin" ng-app="myapp" ng-controller="ctrl">
<table ng-table="tableParams" class="display table table-striped table-bordered">
<thead>
<tr>
<th width="2%">Sr.No</th>
<th width="10%">Category Type <span class="error">*</span></th>
<th width="10%">Product <span class="error">*</span></th>
<th width="10%">Sub Category</th>
</tr>
</thead>
<tr ng-repeat="cap in data">
<td>{{$index+1}}</td>
<td data-title="'Category Type'" sortable="Category Type">
<select class="form-control" id="tags" type="text" ng-model="cap.categoryid" placeholder="Category Type" name="categoryid" required="" ng-init="loadcat()" ng-change="GetProduct(cap.categoryid,$index);GetSubCategory(cap.categoryid,cap.productname)">
<option value="">Select</option>
<option ng-repeat="cat in CategoryArray" value="{{cat.Category_Id}}">{{cat.Category_Name}}</option>
</select>
</td>
<td data-title="'Product'" sortable="Product">
<select class="form-control" type="text" name="productname" ng-model="cap.productname" placeholder="Enter Product Name" required ng-change="GetSubCategory(cap.categoryid,cap.productname)" />
<option value="">select</option>
<option ng-repeat="pro in ProductsArray[$index]" value="{{pro.ProductId}}">{{pro.ProductlName}}</option>
</select>
</td>
<td data-title="'Sub Category1'" sortable="Sub Category1">
<select class="form-control" type="text" name="subcategoryid" ng-model="cap.subcategoryid" id="subcategoryid">
<option value="">Select</option>
<option ng-repeat="subcatid in subcatids" value="{{subcatid.Sub_category_Id}}">{{subcatid.Sub_Category_Name}} </option>
</select>
</td>
<td>
<div class="pull-right">
<a ng-click="addFormField()" ng-if="data.length==$index+1" class='btn btn-default btn-xs' autofocus data-dismiss="modal"> <i class="glyphicon glyphicon-plus"></i></a>
<a ng-click="remove_Row($index)" class='btn btn-primary btn-xs' autofocus data-dismiss="modal"> <i class="glyphicon glyphicon-remove"></i></a>
</div>
</td>
</tr>
</table>
</body>
</html>
I'am getting CategoryArray data using ng-init="loadcat()" on ng-change="GetProduct(cap.categoryid)" of category fetching dynamic data in ProductsArray. And I like also on ng-change="GetSubCategory(cap.categoryid,cap.productname)" of productname to fetch the dynamic data in subcatids
But the problem is while I'am adding one more row, again selecting category the ProductsArray changing for previous row also.
Q: How could I get ProductsArray on every selecting category in ng repeat for every iteration?

forming an array from dynamic input fileds using angularjs

I am working on a employee attendance system where i need to know their attendance status.I am generating a dynamic form which contains a text input field and a checkbox for each employee using angularjs ng-repeat inside a table to know whether the the employee was present or absent along with comments.I want to save the values of these dynamic text filed and checkbox using a single save button.Text fields may have null values or any other values and checkbox may be all checked,all unchecked and few checked and few unchecked. If the check box is checked then i want to save "checked":"yes" otherwise as no.I have also a single date input field to save the record for this particular date.
I think the solution of my situation is forming a dynamic array from inputs and assign it to a variable but and don't know how to form array dynamically in angularjs and then pass the array to a php page.Can you help me on this issue?
My expected array format is :
[{"Did":"10","supervisor":"ms1001","date":"2017-06-01",
"info":
{"eid":"10","checked":"yes","cmnt":"on time"},
{"eid":"20","checked":"NO", "cmnt":"absent"},
{"eid":"30","checked":"yes","cmnt":""},
{"eid":"40","checked":"NO","cmnt":"OK"},
{"eid":"50","checked":"YES","cmnt":""},
{"eid":"60","checked":"YES","cmnt":""},
{"eid":"70","checked":"YES","cmnt":""},
{"eid":"80","checked":"NO","cmnt":"Late"},
{"eid":"90","checked":"YES","cmnt":""}
}];
I will store the input details in attendance table which schema is
attendance(did,eid,date,checked,comment,supervisor_id)
var myApp = angular.module('myApp',['ui.bootstrap']);
myApp.controller('MyCtrl', function($scope) {
$scope.list = [
{"dept_id":"d10","dname":"sales","supervisor":"ms1001"},
{"eid":"10","ename":"nam1"},
{"eid":"20","ename":"nam2"},
{"eid":"30","ename":"nam3"},
{"eid":"40","ename":"nam4"},
{"eid":"50","ename":"nam5"},
{"eid":"60","ename":"nam6"},
{"eid":"70","ename":"nam7"},
{"eid":"80","ename":"nam8"},
{"eid":"90","ename":"nam9"},
{"eid":"120","ename":"nam10"}
];
$scope.did= $scope.list[0].dept_id;
$scope.dname= $scope.list[0].dname;
$scope.sp_name= $scope.list[0].supervisor;
$scope.selectedText = 'Select All';
$scope.isAll = false;
$scope.selectAll = function() {
if($scope.isAll === false) {
angular.forEach($scope.list, function(data){
data.checked = true;
});
$scope.isAll = true;
$scope.selectedText = 'Deselect All';
} else {
angular.forEach($scope.list, function(data){
data.checked = false;
});
$scope.isAll = false;
$scope.selectedText = 'Select All';
}
};
$scope.selectedFriends = function () {
return $filter('filter')($scope.list, {checked: true });
};
//date picker
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
$scope.format = 'dd-MMMM-yyyy';
//end of date picker
});
<html>
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style>
.full button span {
background-color: limegreen;
border-radius: 32px;
color: black;
}
.partially button span {
background-color: orange;
border-radius: 32px;
color: black;
}
</style>
</head>
<div class="container">
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="row">
<div class="col-sm-3" style="background-color:yellow;">
<p>Department ID::{{did}}</p>
</div>
<div class="col-sm-3" style="background-color:skyblue;">
<p>Dept Name:{{dname}}</p>
</div>
<div class="col-sm-3" style="background-color:pink;">
<p>Supervisor name name:{{sp_name}}</p>
</div>
<div class="col-sm-3">
<p class="input-group">
<input type="text" class="form-control" uib-datepicker-popup="{{format}}"
ng-model="list.dt" is-open="opened" min-date="minDate" max-date="'2018-06-22'"
ng-model-options="{timezone: 'UTC'}"
datepicker-options="dateOptions" date-disabled="disabled(date, mode)"
ng-required="true" close-text="Close" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)">
<i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Employee ID</th>
<th>name</th>
<th><label>Attendence</label><br><span id="selectall" ng-click="selectAll()"><input
type="checkbox">{{selectedText}}</span></th>
<th>comment</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="data in list" ng-if="$index">
<td> {{ data.eid }} </td>
<td> {{ data.ename }} </td>
<td> <input type="checkbox" value="{{ data.eid}}" ng-checked="data.checked" ng-model="data.checked"></td>
<td>
<input type="text" ng-model="data.cmnt" ></td>
</tr>
</tbody>
</table>
<pre>{{list}}</pre>
</div>
<button type="button" ng-click="saveAll()">Save all</button>
</div>
</html>
HTML
<table border="1">
<tr>
<td>Employee ID</td>
<td>Name</td>
<td>Attendance</td>
</tr>
<tr ng-repeat="employee in employees">
<td>{{employee.eid}}</td>
<td>{{employee.ename}}</td>
<td><input type="checkbox" name="check" ng-model="employee.att">
</td>
</tr>
</table>
<button ng-click="saveForm()">Save all</button>
<pre>{{employees}}</pre>
JS
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
//initial data to display on table.
$scope.employees = [
{eid:"10",ename:"nam1", att: false},
{eid:"20",ename:"nam2", att: false},
{eid:"30",ename:"nam3", att: false},
];
//on save
$scope.saveForm = function (){
$http({
method: 'POST',
url: '/ana/testone',
data: $.param({formData: angular.copy($scope.employees)}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
console.log(response);
});
}
});
PHP
$data = $_POST['formData'];
echo json_encode($data);

Can't call controller function from view

I want to call the controller function from view.
This my view:
<body>
<div ng-app="appTable">
<div ng-controller="Allocation">
<button ng-click="add()"> Add </button>
<button ng-click="remove()">remove</button>
<table>
<th>
<td>Date</td>
<td>Project</td>
<td>Release</td>
<td>Feature</td>
<td>Module name</td>
<td>Hours spent</td>
<td>Comment</td>
</th>
<tr ng-repeat="data in dataList">
<td><input type="checkbox" ng-model="data.isDelete"/></td>
<td>
<input type="text"
datepicker
ng-model="data.date" />
</td>
<td><input type="text" ng-model="data.dept"/></td>
<td>
<select ng-model="data.release" ng-options="x for x in range">
</select>
</td>
<td>
<select ng-model="data.feature" ng-options="x for x in feature">
</select>
</td>
<td>
<input type = "text" ng-model = "data.modulename">
</td>
<td>
<select ng-model="data.hours" ng-options="x for x in hours">
</select>
</td>
<td>
<input type = "text" ng-model = "data.comment">
</td>
</tr>
</table>
<button ng-click="Submit()">Submit</button>
<table>
<tr ng-repeat="data in displayList">
<div ng-controller="Allocation as vm">
<div>{{vm.postdata(data.date)}}</div>
</div>
<p>Output Message : {{msg}}</p>
<p>StatusCode: {{statusval}}</p>
<p>Status: {{statustext}} </p>
<p>Response Headers: {{headers}} </p>
<td>
<p>{{data.date}}</p>
</td>
<td>
<p>{{data.dept}}</p>
</td>
<td>
<p>{{data.release}}</p>
</td>
<td>
<p>{{data.feature}} </p>
</td>
<td>
<p>{{data.modulename}}</p>
</td>
<td>
<p>{{data.hours}}</p>
</td>
<td>
<p>{{data.comment}}</p>
</td>
</td>
</tr>
</table>
</div>
</div>
</body>
This is script.
<script>
var app = angular.module("appTable", []);
app.controller("Allocation", function($scope) {
$scope.hours = ["1", "2", "3"];
$scope.range = ["1", "2", "3"];
$scope.feature = ["UT", "FSDS", "Coding/Devlopment", "QA"];
$scope.dataList = [{
date: '17/07/2016',
dept: 'OneCell',
release: '1',
feature: "UT",
modulename: "Redundancy",
hours: "1",
comment: "Add extra information"
}];
$scope.add = function() {
var data = {};
var size = $scope.dataList.length;
if (!size) {
$scope.dataList = [{
date: '17/07/2016',
dept: 'OneCell',
release: '1',
feature: "UT",
modulename: "Redundancy",
hours: "1",
comment: "Add extra information"
}];
} else {
size = size - 1;
data.date = $scope.dataList[size].date;
data.dept = $scope.dataList[size].dept;
data.release = $scope.dataList[size].release;
data.feature = $scope.dataList[size].feature;
data.modulename = $scope.dataList[size].modulename;
data.hours = $scope.dataList[size].hours;
data.comment = $scope.dataList[size].comment;
$scope.dataList.push(data);
}
};
$scope.Submit = function() {
$scope.test = "Submit is pressed...";
$scope.displayList = [];
angular.forEach($scope.dataList, function(v) {
if (!v.isDelete) {
$scope.displayList.push(v);
}
});
$scope.dataList.splice(0);
};
$scope.remove = function() {
var newDataList = [];
angular.forEach($scope.dataList, function(v) {
if (!v.isDelete) {
newDataList.push(v);
}
});
$scope.dataList = newDataList;
};
$scope.postdata = function(date) {
var data = {
date: date,
};
$http.post('/add_status/', data).then(function(response) {
if (response.data)
$scope.msg = "Post Data Submitted Successfully!";
}, function(response) {
$scope.msg = "Service not Exists";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});
app.directive("datepicker", function() {
function link(scope, element, attrs, controller) {
// CALL THE "datepicker()" METHOD USING THE "element" OBJECT.
element.datepicker({
onSelect: function(dt) {
scope.$apply(function() {
// UPDATE THE VIEW VALUE WITH THE SELECTED DATE.
controller.$setViewValue(dt);
});
},
dateFormat: "dd/mm/yy" // SET THE FORMAT.
});
}
return {
require: 'ngModel',
link: link
};
});
</script>
As you can see in the view I have called the postdata function of the controller.This function internally uses msg variable.But view is not printing value of this variable.I am very new to Aj. Please help.
You need to make following changes:
Remove ng-controller="Allocation as vm", as you already defined controller above., and you not using this syntax in controller.
after you removed as vm, then no need to vm. calls.
you need to inject $http in your controller., to make API call
See this fiddle demo, I logged dummy text in console for each `submit click.
and to make single call on submit, See this Fiddle
You should return a value in the function or add a scope variable to be shown in the controller's div, because right now you are not showing anything.
<div ng-controller="Allocation as vm">
<div>{{vm.postdata(data.date)}}</div>
<p>Output Message : {{msg}}</p>
<p>StatusCode: {{statusval}}</p>
<p>Status: {{statustext}} </p>
<p>Response Headers: {{headers}} </p>
</div>
Anyway, you should not run procedural function in this way. Bind it to an event, ng-click or something.
And do not create other than td or th child elements in tr.
This is the proper html table structure:
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>

enable/disable button on a table on selection of dropdown using ng-options not working properly

I have a table with a dropdown selection in each row, I wanted to make an upload button (to work) only when the the drop down status is done. Right now its not working properly
fiddle here
<body ng-app='saapp', ng-controller = "homeCtrl">
<body>
<table>
<tr data-ng-repeat="test in tests ">
<td>{{$index+1}}</td>
<td>{{test}}</td>
<td style="color:red"> pending</td>
<td><font size="2" color="red"></font>
<select ng-model="checkStatus" ng-init="checkStatus='NotDone'", ng-options="status.sta as status.name for status in status" ng-change="changePayStatus(checkStatus)"></select>
</td>
<td class="col-md-2">
<P>
<button type="button" ng-show="!pictureEditor" ng-click="pictureEditor = true" ng-disabled="enableUpload" class="btn-primary btn-u-xs">Upload </button>
<div ng-show="pictureEditor">
<input type="file" name="file" onchange="angular.element(this).scope().selectFile(this.files)"/>
<div ng-show="pictureEditor" class="input-group"><span class="input-group-btn">
<button ng-click="saveDiagnosticReport(test, appointmentDetails); pictureEditor = false " class="btn btn-default">Save <i class="input-save fa fa-check-square"></i></button>
<button ng-click="pictureEditor = false" class="btn btn-default">Back <i class="fa fa-undo"></i></button></span></div>
</div>
</P>
</td>
</tr>
<table>
</body>
angular controller
var app = angular.module('saapp',[ ]);
app.controller('homeCtrl', function($scope){
$scope.tests = ["A", "B", "C"]
$scope.status = [{name :"Done", sta : 1}, {name : "NotDone", sta : 0}];
$scope.enableUpload = 1;
$scope.changePayStatus = function(status) {
console.log(status);
if(status == '1') {
$scope.enableUpload = 0;
}
else if(status == "0") {
$scope.enableUpload = 1;
}
};
})
You need to bind each row's upload button's disablity state to different model inside $scope, one way for doing that is to hold each row disablity state in it self,so you need to change tests array to an object like this:
$scope.tests = [{name:"A",disabled:1}, {name:"B",disabled:1}, {name:"C",disabled:1}]
disabled now holds the state of upload button disability for each row.
by changing tests this way, you'll need to change your code like bellow to achieve what you are looking for:
<table>
<tr data-ng-repeat="test in tests ">
<td>{{$index+1}}</td>
<td>{{test.name}}</td>
<td style="color:red"> pending</td>
<td><font size="2" color="red"></font>
<select ng-model="checkStatus" ng-init="checkStatus='NotDone'"
ng-options="status.sta as status.name for status in status"
ng-change="changePayStatus(checkStatus,test)"></select>
</td>
<td class="col-md-2">
<p>
<button type="button" ng-show="!pictureEditor" ng-click="pictureEditor = true"
ng-disabled="test.disabled" class="btn-primary btn-u-xs">Upload </button>
...
</p>
</td>
</tr>
<table>
Edited: As you can see in the HTML,I'm passing test object that I've got from ng-repeat to changePayStatus method, while test is member of tests and we've got tests from the scope, therefore test it self is from the scope and angular will handle changes on it,in views you can pass models that you've got from scope, to controller again and angular handles the rest.
so you also need to change controller like this:
app.controller('homeCtrl', function($scope){
$scope.tests = [{name:"A",disabled:1}, {name:"B",disabled:1}, {name:"C",disabled:1}]
$scope.status = [{name :"Done", sta : 1}, {name : "NotDone", sta : 0}];
$scope.changePayStatus = function(status,testItem) {
console.log(status);
if(status == 1) {
testItem.disabled= 0;
}
else if(status == 0) {
testItem.disabled= 1;
}
};
});
An edited working sample can be found Here
hope that helps.

Iterating over table using Angular

I'm new to angular and js. I did a table (just a header) and a button. When I click the button a new row line is added. Every cell of that row is a form text field. Everithing works fine. Now I'm trying to do a second button, when I click it must iterate over the rows and validate the fields. I'm not finding any documentation about that... so i'm not sure if this mettod (add a new row with a button) is appropiate. That's how I did it:
index.html this contains angular and my script, also contains the routes:
<html ng-app="assets">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="sources/js/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular-route.min.js"></script>
<script>
var assets = angular.module('assets', ['ngRoute']);
assets.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'home.html'
}).
when('/:tipusactius', {
templateUrl: 'tipusactius.html',
controller: 'TipusActiusCtrl'
}).
when('/:tipusactius/alta', {
templateUrl: 'tipusactius-alta.html',
controller: 'AfegirTipusActiusCtrl'
}).
otherwise({
redirectTo: '/'
});
});
assets.controller('TipusActiusCtrl', function ($scope, $http){
$http.get('http://10.0.203.73/WS/ws.php/tipusactius/').success(function(data) {
$scope.tipus_actius = data;
});
// Ordena taula per id desc
$scope.sortField = 'idtipus_actius';
$scope.reverse = false;
});
assets.controller('AfegirTipusActiusCtrl', function ($scope, $http){
// Camps formulari text pla
$scope.nomAtribut = "<input type='text' name='firstname'>";
$scope.mida = "<input type='number' name='firstname'>";
$scope.obligatori = "<input type='checkbox' name='vehicle' value='yes'>";
// Construeix combo
$http.get('http://10.0.203.73/WS/ws.php/getCombo/1').success(function(data) {
$scope.options = data;
});
$scope.atributs = [];
$scope.addField = function() {
$scope.atributs.push($scope.atributs.length);
};
$scope.prioritat = $scope.atributs.length;
});
assets.directive('compile', compile);
function compile($compile)
{
return {
restrict: 'A',
replace: true,
link: linkFunction
};
function linkFunction(scope, element, attrs)
{
scope.$watch(
function (scope)
{
return scope.$eval(attrs.compile);
},
function (value)
{
element.html(value);
$compile(element.contents())(scope);
}
);
}
}
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container" ng-view></div>
</body>
</html>
And this is the view where the table is(tipusactius-alta):
<div class="row">
<div class="col-md-8" ng-controller="AfegirTipusActiusCtrl">
<button ng-click="addField()">Nou atribut</button>
<div>
<table class="table">
<tr>
<td>Nom atribut</td>
<td>Tipus</td>
<td>Mida</td>
<td>Prioritat</td>
<td>Obligatori</td>
</tr>
<tr ng-repeat="atribut in atributs">
<td compile="nomAtribut"></td>
<td>
<select id="tipus">
<option ng-repeat="option in options" value="{{option.idvalors_combo}}">{{option.valor}}</option>
</select>
</td>
<td compile="mida"></td>
<td>
<select id="prioritat">
<option ng-repeat="p in prioritat" value="{{p}}">{{p}}</option>
</select>
</td>
<td compile="obligatori"></td>
</tr>
</table>
</div>
</div>
</div>
</div>
I'm not sure if this has been a good idea. I would like to find a way to iterate over the rows to read cell values, and if the values of all cells from all the rows is ok submit the values to the web service but I have no idea. Any help will be great.
You don't actually need to manipulate html directly. Just use ng-repeat over your data collection. Button should add new items to that collection and angular will create new table row in the document.
I've created small sample here: http://jsfiddle.net/Lvc0u55v/252/
var myApp = angular.module('myApp', []);
myApp.controller('tableCtrl', function($scope) {
$scope.dataTable = [{
"name": "Alex",
"lastName": "Karlov",
"age": 23,
"sex": 1
}];
$scope.options = [{
"value": 1,
"title": "Male"
}, {
"value": 2,
"title": "Female"
}];
$scope.addRow = function() {
var newItem = {
name: "",
lastName: "",
age: "",
sex: ""
}
$scope.dataTable.push(newItem);
};
});
And this is the html (I've created it based on yours code):
<div class="col-md-8" ng-controller="tableCtrl">
<button ng-click="addRow()">Add row</button>
<div>
<table class="table">
<tr>
<td>#</td>
<td>Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Sex</td>
</tr>
<tr ng-repeat="item in dataTable">
<td>{{ $index + 1 }}</td>
<td>
<input type="text" ng-model="item.name" />
</td>
<td>
<input type="text" ng-model="item.lastName" />
</td>
<td>
<input type="text" ng-model="item.age" />
</td>
<td>
<select ng-options="option.value as option.title for option in options" ng-model="item.sex"></select>
</td>
</tr>
</table>
</div>
</div>
In that sample I've put all my data into dataTable variable. When I want to add one more row, I just need to add new empty object (or with predefined values) into dataTable collection. Angular will do the trick.

Categories