Currently, I am working on an add/edit form using angularJS. Within this project, there are two templates - one for displaying a list of items and another for the form itself. While adding new items works smoothly, I have encountered some challenges when it comes to updating existing ones. I have defined the following routes, utilizing a single controller to manage category-related operations:
$routeProvider.when('/category', {templateUrl:'templates/category.html', controller: 'categoryCtrl'});
$routeProvider.when('/category/:categoryId?', {templateUrl:'templates/editcategory.html', controller:'categoryCtrl'});
Within the category.html template, there is a button that redirects to the edit template for adding new categories.
<button class="btn btn-primary" ng-click="createCategory()">Add Category</button>
Additionally, each item in the list has its own "Edit" button for updating purposes.
<button class="btn btn-warning" ng-click="editCategory(category)">Edit</button>
Below is the content of the editCategory.html template used for both adding and editing categories:
<div class="container">
<form class="form-horizontal" id="categoryForm" name="categoryForm" ng-controller="categoryCtrl" >
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" name="name" ng-model="category.name" class="form-control" required></input>
<span ng-show="form.name.$dirty && form.name.$error.required">Category name is required</span>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" value="submit" class="btn btn-primary" ng-click="addCategory(category)"
ng-disabled="categoryForm.$invalid">Create Category</button>
<button type="btn" value="cancel" class="btn btn-danger" ng-click="cancelBtn()">Cancel</button>
</div>
</div>
</form>
</div>
Lastly, here is the categoryCtrl script that controls the functionality:
myApp.controller('categoryCtrl', function($scope, $http, $location) {
$scope.title ="Categories";
$scope.categories = [];
$scope.addCategory = function(category){
$http.post('http://localhost/myappi/API/index.php/Api/categories',category).
success(function(data) {
$scope.categories.push(data);
})
.error(function(err) {
console.log(err);
})
$location.path('/category');
};
$scope.editCategory = function(categoryData)
{
var id = categoryData.id;
$scope.category = {};
$scope.category = categoryData;
console.log('scope data is ', $scope.category);
$location.path('/category/'+id);
};
//go to the form to add a new category
$scope.createCategory = function() {
$location.path('/category/'+'new');
};
});
I initially assumed that setting $scope.category = category would automatically populate the form fields with the corresponding values. Do you think it's appropriate to use the same route and template for both adding and editing actions?