Update row in angular-smart-table - angularjs

In my app i list users in a table via angular smart table. Now i would like to update a record once i modified it. I can't find any function with which i can change the user in my rowCollection so my list view reflects those changes directly.
This is my Service to receive my users from the API
services.factory('Users', function($resource) {
return $resource('/api/v1.0.0/users/:id', {id: '#id'}, {
update: {
method: 'PUT'
}
});
});
This is my List Controller to get the data from my factory. It also has the delete function. The delete function works fine - it just removes one index from the usersRowCollection. The API removes it from the DB.
app.controller('UsersCtrl', ['$scope', '$resource', 'Users',
function ($scope, $resource, Users) {
// Defines how many items per page
$scope.itemsByPage = 10;
// Create a reference object of usersRowCollection for smart table
$scope.usersRowCollection = Users.query();
$scope.usersDisplayedCollection = [].concat($scope.usersRowCollection);
/**
* Function to send a DELETE request to the API
* and to remove the row from the table
* #param user The row item
*/
$scope.deleteUser = function (user) {
// Send request to the API
user.$delete(function () {
// Remove this line from the table
var index = $scope.usersRowCollection.indexOf(user);
if (index !== -1) {
$scope.usersRowCollection.splice(index, 1);
}
})
}
}]);
This is my edit controller where i try to make the magic happen. the $scope.user.$update() function sends the changed data to the API - now i just need to get the changes reflected in my users list to which i redirect via $state.go('app.users.list') (ui-router)
app.controller('UsersEditCtrl', ['$scope', '$state', '$stateParams', 'Users',
function ($scope, $state, $stateParams, Users) {
$scope.updateUser = function () {
$scope.user.$update(function () {
$state.go('app.users.list');
//console.log($scope.user);
//console.log($scope.usersRowCollection);
//var index = $scope.usersRowCollection.indexOf($scope.user);
//console.log($scope.user.id);
// Remove this line from the table
var index = $scope.usersRowCollection.indexOf($scope.user);
if (index !== -1) {
$scope.usersRowCollection.splice(index, 1);
}
//$scope.user = Users.get({id: $scope.user.id});
//$scope.usersRowCollection.update();
// todo Update the changed entry in the table
});
};
// Loads the users json data from the REST Api
$scope.loadUser = function () {
//console.log('loadUser');
$scope.user = Users.get({id: $stateParams.id});
};
$scope.loadUser();
}]);
Thats my HTML - as you can see i use the st-safe-src attribute. If i understood correctly, it should recognice the changes and reflect them automatically.
<table st-table="usersDisplayedCollection" st-safe-src="usersRowCollection" class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
<th>ACTIVE</th>
<th>CREATED_AT</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in usersDisplayedCollection">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>{{ user.active }}</td>
<td>{{ user.created_at }}</td>
<td>
<button type="button" confirm-button="deleteUser(user);" confirm-message="Wirklich löschen?"
class="btn btn-sm btn-danger">
<i class="fa fa-times"></i> Delete
</button>
<a href="#" ui-sref="app.users.edit({id:user.id})" class="btn btn-sm btn-warning">
<i class="fa fa-pencil"></i> Edit
</a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="7" class="text-center">
<div st-pagination="" st-items-by-page="itemsByPage" st-displayed-pages="7"></div>
</td>
</tr>
</tfoot>
</table>
Edit form:
<form class="form-horizontal" role="form" ng-submit="updateUser()">
<div class="form-group">
<label>ID</label>
<input type="text" disabled="disabled" class="form-control" value="{{ user.id }}">
</div>
<div class="form-group">
<label for="name">NAME</label>
<input type="text" ng-model="user.name" class="form-control" id="name" placeholder="YOUR NAME">
</div>
<div class="form-group">
<label for="email">E-MAIL</label>
<input type="email" ng-model="user.email" class="form-control" id="email" placeholder="YOUR EMAIL">
</div>
<div class="radio">
<label>
<input type="radio" ng-model="user.active" name="active" id="active" value="1">
ACTIVE
</label>
<label>
<input type="radio" ng-model="user.active" name="active" id="inactive" value="0">
INACTIVE
</label>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
ABBRECHEN
<button type="submit" class="btn btn-default">SPEICHERN</button>
</div>
</div>
</form>
So, how can i reflect the changes i do in my form view directly after saving in my list view?

Related

using Angularjs How to bind dropdown value control from the table by clicking on edit button?

i only bind the drop-down related value, by clicking on edit button within table, its not working within drop-down
Here is my angularjs code
myapp = angular
.module('myapp', ["ui.router", 'ngAnimate', 'angular-loading-bar', 'ui-notification', 'smart-table', 'ui.bootstrap'])
.controller('DemoCtrl', function ($scope, $interval, Notification, cfpLoadingBar, $http) {
GetAll();
function GetAll() {
$http.get("/api/AddCatagories").then(function (response) {
$scope.cate = response.data
}, function () {
alert("Error")
})
}
$scope.subcateedit = function (Id) {
$http.get("/api/AddSubCatagories/" + Id).then(function (response) {
cfpLoadingBar.start();
$scope.SubCata = response.data
cfpLoadingBar.complete();
})
}
})
Html Table Code is here you can view all code..i only bind the drop-down related value, by clicking on edit button within table, its not working within drop-down
<table st-table="sub" st-safe-src="subcate" class="table table-striped">
<thead>
<tr>
<th style="color:black">Id</th>
<th style="color:black" width="100px">SubCatagoryName</th>
<th style="color:black" width="100px">CatagoryName</th>
<th style="color:black">Action</th>
</tr>
<tr>
<th colspan="5">
<label>Search..</label>
<input st-search placeholder="search" class="input-sm form-control" type="search" />
</th>
</tr>
</thead>
<tbody>
<tr st-select-row="row" st-select-mode="multiple" ng-repeat="row in sub">
<td style="color:black">{{row.Id}}</td>
<td style="color:black">{{row.SubCataName}}</td>
<td style="color:black">{{row.tblcatagory.CataName}}</td>
<td>
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default" ng-click="subcateedit(row.Id)">
<i class="glyphicon glyphicon-pencil" style="color:black">
</i>
</button>
<button type="button" class="btn btn-danger" ng-click="subcatedelete(row.Id)">
<i class="glyphicon glyphicon-trash" style="color:white">
</i>
</button>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" class="text-center">
<div st-pagination="" st-items-by-page="itemsByPage"></div>
</td>
</tr>
</tfoot>
</table>
html form code:
<section class="panel">
<header class="panel-heading danger">
Add Catagory
</header>
<div class="panel-body" ng-controller="DemoCtrl">
<div ng-form="frm" name="loginForm"
class="pure-form pure-form-aligned" autocomplete="off">
<div class="position-center">
<div class="form-group" ng-class="{ 'has-error' :loginForm.ddl.$invalid && !loginForm.ddl.$pristine }">
<label>SubCatagory Name*</label>
<p>{{ SubCata.tblcatagory.CataName }}</p>
<select required name="ddl"
value="{{ SubCata.tblcatagory.CataName }}"
class="form-control"
ng-model="SubCata"
ng-options="item.CataName for item in cate">
</select>
<p ng-show="loginForm.ddl.$dirty && loginForm.ddl.$error.required"
class="help-block">Catagory Name is required</p>
</div>
<div class="form-group" ng-class="{ 'has-error' :loginForm.name.$invalid && !loginForm.name.$pristine }">
<label>SubCatagory Name*</label>
<input type="text" name="name" class="form-control" ng-model="SubCata.SubCataName"
ng-minlength="3" ng-maxlength="20" required>
<p ng-show="loginForm.name.$dirty && loginForm.name.$error.required"
class="help-block">SubCatagory Name is required</p>
<p ng-show="loginForm.name.$error.minlength" class="help-block">
SubCatagory Name is too short.
</p>
<p ng-show="loginForm.name.$error.maxlength" class="help-block">
SubCatagory Name is too long.
</p>
</div>
<button type="submit" class="btn btn-primary" ng-click="submitSubForm(loginForm.$valid , SubCata)"
ng-disabled="loginForm.$invalid">
Submit
</button>
</div>
</div></div>
</section>
UPDATE
now one issue is that ng-model="SubCata.tblcatagory.CataName" due to this i can't get the this {{SubCata.tblcatagory.Id}} id in the controller $scope
<select required name="ddl" class="form-control"
ng-model="SubCata.tblcatagory.Id"
ng-options="item.Id as item.CataName for item in cate">
</select>
i get id from this code
<label>SubCatagory Name*</label>
<p>{{ SubCata.tblcatagory.CataName }}</p>
<select required name="ddl"
value="{{ SubCata.tblcatagory.CataName }}"
class="form-control"
̶n̶g̶-̶m̶o̶d̶e̶l̶=̶"̶S̶u̶b̶C̶a̶t̶a̶"̶
̶n̶g̶-̶o̶p̶t̶i̶o̶n̶s̶=̶"̶i̶t̶e̶m̶.̶C̶a̶t̶a̶N̶a̶m̶e̶ ̶f̶o̶r̶ ̶i̶t̶e̶m̶ ̶i̶n̶ ̶c̶a̶t̶e̶"̶
ng-model="SubCata.tblcatagory.CataName"
ng-options="item.CataName as item.CataName for item in cate">
</select>

selecting the item to edit AngularJS

My problem is I expected to get the element clicked getting selected for edit,I am in fact getting the addExpert view but my element is not already selected considering that I have data-ng-model="Item.genre and data-ng-model="Item.rate on my 2. select what do I miss?
here s the complete
experience view --
<div class="form-group">
<label for="txtName">Company Name</label>
<input type="text" id="search" data-ng-model="search" class="form-control" />
</div>
<table class="table table-hover">
<tbody>
<tr>
<th>Name</th>
<th>Genre</th>
<th>Rating</th>
</tr>
<tr data-ng-repeat="item in message | filter:search" data-ng-click="editItem($experience)">
<td>{{ item.name}}</td>
<td>{{ item.genre}}</td>
<td>{{ item.rate}}</td>
</tr>
</tbody>
</table>
<button class="btn btn-primary" data-ng-click="addExperience()">
add experience
</button>
addexpertView
<div class="form-group">
<label for="chcTech">Tech</label>
<select name="chcTech" id="chcTech" class="form-control" data-ng-model="Item.genre">
<option value="c#">c#</option>
...
</select>
</div>
<div class="form-group">
<label for="chcRate">Rate</label>
<select name="chcRate" id="chcRate" class="form-control" data-ng-model="Item.rate">
<option value="1">1</option>
....
</select>
....
</div>
edit controller
cvApp.controller("editExperienceController",["$scope", "$location", "$routeParams","experienceService",
function($scope, $location, $routeParams, experienceService){
$scope.Item= experienceService.getExperience()[parseInt($routeParams.FOO)];
$scope.save=function(){
//save
$location.path("/about");
}
$scope.cancel=function(){
$location.path("/about");
}
}])
config of the routeProvider
cvApp.config(function($routeProvider) {
$routeProvider
....
.when('/about/:FOO', {
templateUrl: 'pages/addExpert.html',
controller: 'editExperienceController'
})
...
.otherwise({
redirectTo:"pages/home"
});
});
getExperience function in a service
cvApp.factory("experienceService", ["$rootScope", function($rootScope) {
var svc = {};
var message = [
....
{
name: "Azure",
genre: ".net",
rate: "4"
}];
svc.getExperience=function(){
return message;
};
....
}]);
in the experience view it's not $experience but $index
<tr data-ng-repeat="item in message | filter:search" data-ng-click="editItem($index)">

AngularJS Service not calling controller to get updated data after CRUD operation

I am beginner in AngularJS and trying to create a master data entry screen, where upper portion containing form fields & lower portion containing table(GridView) to display all master entries. Grid showing all the data when i initially run the application. If i add/Edit any new/old records, the updated data not reflected in the gridview. (i.e) If i add any new entry, it is saving into the DB through service, but not reflecting in the GridView. Even if i navigate through menu also not displaying the updated data in the grid. But if i press Ctrl + F5, it is showing updated data in the Grid. Alsp If i close the browser & re run the application then the updated records displaying in the Gridview. Below is my code. Please help.. Thank you.!
Index.cshtml
<div class="row">
<div class="col-md-12">
<h3 class="page-header">
Component Master
</h3>
<div class="col-md-12">
<div class="alert alert-dismissible alert-danger" ng-show="ComponentForm.$invalid && submitted">
<button type="button" class="close" aria-hidden="true" data-dismiss="alert">
×</button>
<p ng-show="ComponentForm.ComponentName.$error.required && (ComponentForm.ComponentName.$dirty || submitted)">
- Component Name is required.</p>
<p ng-show="ComponentForm.ComponentName.$error.minlength && (ComponentForm.ComponentName.$dirty || submitted)">
- Component Name should be minimum 5 char long.</p>
<p ng-show="ComponentForm.Language.$error.required && (ComponentForm.Language.$dirty || submitted)">
- Language Selection is required.</p>
</div>
</div>
<div class="col-md-12">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">
Panel success</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<!-- FORM : YOU CAN DISABLE, HTML5 VALIDATION BY USING "novalidate" ATTRIBUTE-->
<form name="ComponentForm" class="form-inline" novalidate>
<!-- COMPONENT NAME -->
<div class="form-group" ng-class="{ 'has-error' : ComponentForm.ComponentName.$invalid && (ComponentForm.ComponentName.$dirty || submitted) }"
style="margin: 10px;">
<label style="margin-right: 10px;">
Component Name</label>
<input type="text" name="ComponentName" ng-model="ComponentModel.ComponentName" class="form-control"
placeholder="Component Name..." ng-minlength="5" ng-required="true" />
<input type="hidden" data-ng-model="ComponentModel.ComponentID" />
<input type="hidden" data-ng-model="ComponentModel.IsActive" />
<input type="hidden" data-ng-model="UserID" />
</div>
<!-- LANGUAGE -->
<div class="form-group" style="margin: 10px;" ng-class="{ 'has-error' : ComponentForm.Language.$invalid && (ComponentForm.Language.$dirty || submitted) }">
<label style="margin-right: 10px;">
Language</label>
<select name="Language" data-ng-model="ComponentModel.Language" class="form-control"
ng-required="true">
<option value="" title="Select">Select</option>
<option value="English" title="English">English</option>
<option value="Spanish" title="Spanish">Spanish</option>
</select>
</div>
<!-- ng-disabled FOR ENABLING AND DISABLING SUBMIT BUTTON -->
<!-- SAVE BUTTON -->
#*<button type="submit" class="btn btn-info" ng-disabled="ComponentForm.$invalid" value="Add">Add</button>*#
<button type="submit" class="btn btn-primary" ng-click="SaveComponent(ComponentModel);"
ng-value="Add">
Add
</button>
<button type="submit" class="btn btn-warning" ng-click="ClearComponent();" value="Clear">
Clear
</button>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr class="success">
<th class="text-center">
ComponentID
</th>
<th class="text-center">
Component Name
</th>
<th class="text-center">
Language
</th>
<th class="text-center">
IsActive
</th>
<th class="text-center">
Last Modified By
</th>
<th class="text-center">
Last Modified Date
</th>
<th class="text-center">
Action
</th>
</tr>
<tr style="height: 250px; border: 2px solid #ecf0f1;" data-ng-show="ShowEmptyRow">
<th colspan="7" class="text-center" style="vertical-align: middle;">
<label class="control-label">
No Records Found.</label>
</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="Component in ComponentMaster" data-ng-show="!ShowEmptyRow" ng-class="{'danger':!Component.IsActive}">
<td style="vertical-align: middle; text-align: center;">
{{ Component.ComponentID}}
</td>
<td style="vertical-align: middle;">
{{ Component.ComponentName}}
</td>
<td style="vertical-align: middle;">
{{ Component.Language}}
</td>
<td style="vertical-align: middle; text-align: center;">
<div class="checkbox">
<label>
<input type="checkbox" disabled="disabled" ng-checked="Component.IsActive" /></label>
</div>
</td>
<td style="vertical-align: middle;">
{{ Component.ModifiedBy}}
</td>
<td style="vertical-align: middle; text-align: center;">
{{ Component.ModifiedDate}}
</td>
<th style="vertical-align: middle; text-align: center;">
<span class="btn btn-info btn-sm" ng-show="Component.IsActive" ng-click="EditComponent(Component.ComponentID);">
Edit</span> <span class="btn btn-danger btn-sm" ng-show="Component.IsActive" ng-click="ActivateDeActivateComponent(Component.ComponentID,false,ComponentModel.ModifiedBy);">
Delete</span> <span class="btn btn-info btn-sm" ng-show="!Component.IsActive" ng-click="ActivateDeActivateComponent(Component.ComponentID,true,ComponentModel.ModifiedBy);">
Activate</span>
</th>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Angular Script:
var AngularApp = angular.module("AngularApp", ['ngRoute']);
AngularApp.controller("ConfigurationController", ['$scope', 'ConfigurationService', function ($scope, ConfigurationService) {
$scope.ComponentMaster = [];
GetComponentMasterDetails();
/*------------- Save Component ---------------- */
// When i click Save btn - executing this function. control comes here...
$scope.SaveComponent = function (ComponentModel) {
$scope.submitted = true;
if ($scope.ComponentForm.$valid) {
ComponentModel.ModifiedBy = $scope.UserID;
// control comes here... & Calling method "SaveComponentMaster" inside ConfigurationService & returned execution message
var Msg = ConfigurationService.SaveComponentMaster(ComponentModel);
Msg.then(function (response) {
if (response.data != "") {
alert(response.data);
}
else {
// After Saved into DB showing below alert message.
alert("Data Saved Successfully.");
// Calling below method to get the updated records from DB
GetComponentMasterDetails();
}
}, function (error) {
alert(error.data);
});
}
else {
alert("Please correct errors!");
}
}
/**----------------------------------------------------- */
// Below method is calling...
function GetComponentMasterDetails() {
// Call moves to ConfigurationService Service method...
var ComponentMaster = ConfigurationService.GetComponentMasterDetails();
ComponentMaster.then(function (response) {
if (response.data != "") {
// This service call returning the old data only.
// Updated/Added entry details not reflecting in the returned object.
// This is the reason why it is showing old records only in the Grid.
$scope.ShowEmptyRow = false;
$scope.ComponentMaster.length = 0;
angular.extend($scope.ComponentMaster, response.data);
}
else {
$scope.ShowEmptyRow = true;
$scope.ComponentMaster.length = 0;
}
}, function (error) {
alert(error.data);
});
}
} ]);
AngularApp.service("ConfigurationService", function ($http) {
// Call comes here...
this.GetComponentMasterDetails = function () {
// Call comes here... But this $http.get - not calling MVC controller Action method.
// I kept my breakpoint in MVC controller method, but not executed the method.
// So this Service just returning old records. This is the reason the View showing old records.
// If i press Ctrl + F5, it is calling MVC controller message & showing the updated records.
return $http.get('/Configuration/GetComponentMasterDetails');
};
// Control comes here... Then calling MVC controller Action method.. Saving data into DB & returned execution message.
this.SaveComponentMaster = function (ComponentModel) {
var response = $http({
method: 'POST',
url: '/Configuration/SaveComponentMaster/',
data: { ComponentModel: ComponentModel }
});
return response;
};
});
MVC Controller
[NoCache]
[HttpGet]
public ActionResult GetComponentMasterDetails()
{
RNDDBContext dbContext = new RNDDBContext();
var result = dbContext.ExecuteStoreQuery<ComponentModel>("exec PROC_GET_COMPONENT_MASTER_DETAILS").ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
[NoCache]
[HttpPost]
public JsonResult SaveComponentMaster(ComponentModel ComponentModel)
{
RNDDBContext dbContext = new RNDDBContext();
var result = dbContext.ExecuteStoreQuery<string>("exec PROC_SAVE_COMPONENT_MASTER #ComponentID,#ComponentName,#Language,#IsActive,#ModifiedBy",
new SqlParameter("ComponentID", ComponentModel.ComponentID),
new SqlParameter("ComponentName", ComponentModel.ComponentName),
new SqlParameter("Language", ComponentModel.Language),
new SqlParameter("IsActive", ComponentModel.IsActive),
new SqlParameter("ModifiedBy", ComponentModel.ModifiedBy)
).FirstOrDefault();
return Json(result, JsonRequestBehavior.AllowGet);
}
public class NoCache : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
base.OnResultExecuting(filterContext);
}
}
Initialize your $scope.ComponentMaster on the top of controller
AngularApp.controller("ConfigurationController", ['$scope', 'ConfigurationService', function ($scope, ConfigurationService) {
$scope.ComponentMaster = [];
GetComponentMasterDetails();
and just empty that, then repopulate once you call GetComponentMasterDetails()
function GetComponentMasterDetails() {
var ComponentMaster = ConfigurationService.GetComponentMasterDetails();
ComponentMaster.then(function (response) {
if (response.data != "") {
$scope.ShowEmptyRow = false;
// Empty the ComponentMaster array
$scope.ComponentMaster.length = 0;
// Add the retrieved data
angular.extend($scope.ComponentMaster, response.data)
}
else {
$scope.ShowEmptyRow = true;
// Empty the ComponentMaster array
$scope.ComponentMaster.length = 0;
}
}, function (error) {
alert(error.data);
});
}
This issue is similar to this

Cannot get input form items to populate table

I'm currently building a simple little app to as I learn angular.js, and am having a bit of trouble populating a table with the data keyed in by the user. I'm receiving an error:
Cannot read property 'push' of undefined
The JS is below:
var app = angular.module('yardApp', []);
app.controller('mainController', function($http){
var yardSale = this;
yardSale.forSale = [];
yardSale.login = function(){
yardSale.loggedIn = true;
$http({
method: "POST",
url: "/user",
data: { username:yardSale.username }
}).then(function(result){
console.log(result.data);
yardSale.userId = result.data._id;
yardSale.userId = result.data.username;
});
};
yardSale.addItem = function(){
console.log(yardSale.item.product);
yardSale.items.push(yardSale.item);
// yardSale.item = {};
};
}):
The html looks like:
<div>
<h1>Welcome to the Yard Sale!!</h1>
<h2 ng-hide="yardSale.loggedIn"> Plese login to get started.</h2>
<h2 ng-show="yardSale.loggedIn">Welcome {{ yardSale.username }}!</h2>
<h2 ng-show="yardSale.loggedIn">Have anything you'd like to sell?</h2>
<h3 ng-show="yardSale.loggedIn">Please, list it here!</h3>
</div>
<form ng-submit="yardSale.login()" ng-hide="yardSale.loggedIn">
<input type="text" placeholder="Please enter a username" ng-model="yardSale.username">
<input class="btn btn-primary" type="submit" value="login">
</form>
<div class="row" ng-show="yardSale.loggedIn">
<form ng-submit="yardSale.addItem()">
<input type="text" placeholder="Item for Sale" ng-model="yardSale.item.product">
<input type="text" placeholder="Price you'd like" ng-model="yardSale.item.price">
<input type="date" placeholder="Date Listed" ng-model="yardSale.item.date">
<input class="btn btn-primary" type="submit" value="add">
</form>
<table class="col-md-6 col-md-offset-4 table-bordered">
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th>Date Listed</th>
</tr>
</thead>
<tbody>
<tr ng-repeat=" item in yardSale.items">
<td>{{ item.product }}</td>
<td>{{ item.price | currency }}</td>
<td>{{ item.date | date }}</td>
</tr>
</tbody>
</table>
</div>
i can console log yardsale.item.product and see what I enter, but cannot populate it to the table
You get the error cannot read property push of undefined because of your variable called items. Try to do add yardSale.items = [] after this line of code aka your constructor.
var yardSale = this;
yardSale.forSale = [];
yardSale.items = [];
cannot read property push of undefined
This error appears when you are trying to access the value of a variable which is not declared. In this case yardSale.items is never declared. The compiler should be made known of such an attribute exists for the object yardSale, also whether that attribute (ie items) is an object or an array. Hence the answer by #amcpanaligan is a correct solution. you need to declare it as:
yardSale.items = [];
The try:
yardSale.items.push(yardSale.item);
It will work.

AngularJS: ng-submit not working

My addAct() funtion was working fine before, until I tried refactoring the index table. Now it isn't responding. Nothing is appearing in the console, for example. Maybe someone can help me figure out what's going on. I use the _form.html partial twice, but take a look at the row with id="newAct"
acts/templates/index.html
<div class="actions_body">
<div class="container">
<h2>Listing Actions</h2>
<div class="body">
<table class>
<thead>
<tr class="row">
<th class="col-md-2 active">
<label>Name</label>
</th>
<th class="col-md-5">Description</th>
<th class="col-md-2">Inspires</th>
<th colspan="2" class="col-md-2">Modify</th>
</tr>
</thead>
<tbody ng-repeat="act in acts">
<tr class="row">
<td class="col-md-2">{{act.name}}</td>
<td class="col-md-5">{{act.description}}</td>
<td class="col-md-2">{{act.inspires}}</td>
<td class="col-md-1"><button ng-click="updateActShow=true">Edit</button></td>
<td class="col-md-1"><button ng-click="deleteAct(act)">Delete</button>
<tr ng-show="updateActShow" ng-include="'acts/templates/_form.html'"></tr>
</tbody>
<tbody>
<tr class="row">
<button ng-click="newActShow=true">New Action</button>
<button ng-click="newActShow=false">Hide</button>
</tr>
<tr ng-show="newActShow" id="newAct" ng-include="'acts/templates/_form.html'"></tr>
</tbody>
</table>
</div>
</div>
</div>
acts/templates/_form.html
<div class="row" ng-controller="ActsController">
<form ng-submit="addAct()">
<td class="col-md-2">
<label for="newActName">Name</label>
<input type="text" ng-model="newAct.name" id="newActName" placeholder="Name" class="form-control">
</td>
<td class="col-md-4">
<label for="newActDescription">Description</label>
<input type="textarea" ng-model="newAct.description" id="newActDescription" placeholder="Description" class="form-control">
</td>
<td class="col-md-2">
<label for="newActInspires">Inspires</label>
<input type="number" ng-model="newAct.inspires" id="newActInspires" placeholder="Inspires" class="form-control">
</td>
<td class="col-md-2">
<input type="submit" value="+" class="btn btn-success">
</td>
</form>
</div>
acts/controllers/ActsController.js
controllers = angular.module('controllers');
controllers.controller('ActsController', [
'$scope',
'$routeParams',
'$location',
'$resource',
function($scope,$routeParams,$location,$resource) {
var Act = $resource('/acts/:actId', {
actId: "#id",
format: 'json'
}, {
'create': {
method: 'POST'
}
});
$scope.acts = Act.query();
$scope.addAct = function() {
act = Act.save($scope.newAct, function() {
$scope.acts.push(act);
$scope.newAct = '';
});
}
$scope.deleteAct = function(act) {
act.$delete();
$scope.acts.splice($scope.acts.indexOf(act), 1);
}
$scope.linkToShowAct = function(act) {
return $location.path('/acts/' + act.id);
}
}]);
You table is outside of ActsController scope. You need to put ng-controller="ActsController" on one of the elements surrounding table.

Resources