Sending information from an AngularJS selected item to an edit form

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?

Answer №1

Put it simply, whenever the route changes, the category controller is reset along with its $scope. It's advisable to store the data in a factory or service for persistence. Check out this link for more information:

Answer №2

To transfer data between controllers, you have the option to either utilize the $broadcast service and send an object through it or create a custom service for data persistence.

It is advised against using a custom service for data persistence because the variables in the service may lose their values if the page is refreshed, making it highly unreliable for maintaining state. Instead, opt for using $broadcast to pass data between different controllers. For instance, broadcasting an event from one controller can be done as shown below:

$rootScope.$broadcast("editItem",{"category": yourValue});

In another controller, you can capture this event like so:

$scope.$on("editItem", function(event, args) {
  console.log(args.category);
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function inputLocalFont.addEventListener does not exist and cannot be executed

Help needed! I created a code to add images using PHP and JS, but I'm encountering an error in my JS that says: inputLocalFont.addEventListener is not a function Here's the code snippet: <div> <img src="<?php echo $img_path.& ...

The confusion surrounding navigation in Angular's single-page applications

I'm struggling to grasp how Angular handles routing in my single-page application. Here's my issue: When I type in the url: localhost:3000/streams/ I expect the 'streams' page to load. My understanding was this: My express serve ...

Be mindful of potential missing dependencies when utilizing event listeners and states within useEffect

Whenever I utilize the addEventListener() method alongside trying to access some state within the useEffect, I consistently face the same issue. Adding the state as a dependency is not an option, as that would result in multiple event listeners being creat ...

AngularJS provides a way to create opening pages with clickable buttons for a

I'm struggling to implement buttons that switch ons-templates when clicked. I've been following this example as a reference: Here's the code snippet I've been working on, but it just won't cooperate: <!doctype html> &l ...

Convert a single object into a JSON string representation on each line

Can you convert the following data into the desired format through stringification? Data: let result = JSON.stringify([ { "Color": "Red", "Type":"Fast" }, { "Color": "Blue&quo ...

What could be the reason why my useRouter function isn't working as expected?

I'm currently working on developing an App using nextjs 13 and the new App router feature (https://nextjs.org/blog/next-13-4) : I've encountered a navigation issue despite following the documentation diligently. To illustrate, here's a bas ...

Expanding the jQuery AutoComplete Plugin: A Guide to Implementing the bind keyup Event

Currently, I am utilizing a plugin that enhances the features of the jQuery AutoComplete UI Plugin: https://github.com/experteer/autocompleteTrigger/blob/master/jquery-ui.autocompleteTrigger.js Within the select method, an event and ui variable are passe ...

Including a variable in an array within a function

I'm encountering an issue with inserting a variable into my array. Below is the code snippet: var data = new Array(); google.load("feeds", "1"); function initialize() { var feed = new google.feeds.Feed("http://www.ntvmsnbc.com/id/24927681/device/r ...

Unlocking the Power of Angular: Understanding the Relationship between Controllers and Directives

Currently delving into the world of Angular and encountering a hurdle in accessing controller scope from a directive. The $scope.vojta has already been populated in the controller, but I'm unable to print it from the directive. <div ng-controller= ...

How effective is Dojo CodeGlass?

When working with Dojo, I have encountered a situation where the sample codes should be functional based on the references provided. However, after attempting to run the code, I am faced with a blank page. It seems as though I may have overlooked somethi ...

Iterate over the array and eliminate any stylesheets

Currently working on a website using WordPress, and dealing with some unwanted css files that come with certain plugins. I've been attempting to remove these stylesheets with JavaScript but keep running into an error saying Failed to execute 'qu ...

Save information to a server-side .xml file with the use of either JavaScript or PHP

I have a website built using HTML and JavaScript. Currently, I am successfully retrieving data from a server-side .xml file on the site. Everything is working perfectly! However, I am facing issues with allowing users to input data into a field and save ...

Interact with SOAP web service using an Angular application

I have experience consuming Restful services in my Angular applications, but recently a client provided me with a different type of web service at this URL: http://123.618.196.10/WCFTicket/Service1.svc?wsdl. Can I integrate this into an Angular app? I am ...

I encountered an error stating that "next is not a function." Interestingly, this code works perfectly fine with another source that was recommended by a friend

const express=require('express'); const app=express() //middleware const customMiddleware=(req,res,next)=>{ console.log('this is a custom middleware that will be executed before the route handler'); next(); } customMiddlewar ...

The JS content failed to load into the HTML page

I need help creating a workout tracker using two JS files. The main.js file is responsible for loading content from the second file (workoutTracker.js) into the index.html. However, I'm facing an issue where the content is not being displayed on the p ...

Retrieve data from an array within the user Collection using Meteor and React Native

I need assistance with retrieving the entire array [votes] stored within the User Collection. Below is the JSON structure { "_id" : "pziqjwGCd2QnNWJjX", "createdAt" : ISODate("2017-12-21T22:06:41.930Z"), "emails" : [ { "a ...

The ng-click function seems to be malfunctioning within the Angular JS framework

Whenever a list element is clicked, I want to change the scope value and also trigger an onclick function. However, in this particular code, ng-click is not functioning when we add a label for the list element. Here is the code snippet: <ul class="" ...

Encountering difficulties in creating an app with Apache Cordova

After setting up the proxy settings, I attempted to create a new app named "hello" using Cordova with the following commands: npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080 The creation comman ...

What steps should I take to make this slider functional?

How can I achieve a sliding effect on this code? I want the div to slide out when the button is clicked, but I also want the button itself to move. Additionally, how can I ensure that the image and text are displayed in two columns? In my IDE, it appears a ...

tips and tricks for adding content to json with the help of jquery/javascript

Is it possible to include text in a JSON array using jQuery or Javascript? Assuming that there is data in the following format: A list of numerical codes stored in a text file as 123, 456, 789 I am looking to convert them into a JSON array using JavaScr ...