Generate a compilation of products developed with the help of angularjs

I have a request to make a list of items using Directives and share them through controllers.

Check out my code example on plunker: Code Example

Below is the JavaScript code:

var app = angular.module('app', []);

app.controller("BrunchesCtrl", function ($scope, $log) {
    $scope.brunches = [];

    $scope.addNew = function () {
        $scope.brunches.push({ address: "" });
    };
    $scope.$watch('brunch.address', function(value) {
        $scope.address = value;
        $log.info($scope.address);
    });

    $scope.$watch(function() { return $scope.brunches.length; }, function() {
        $scope.brunches = $scope.brunches.map(function (brunch) {
            return brunch;
        });
    });
});

app.directive('brunchesView', function ($compile) {
    return {
        restrict: 'E',
        templateUrl: 'brunch.html',
        controller: 'BrunchesCtrl',
        replace: true,
        link: function (scope, element, attrs, controller) {

        }
    };
});

app.directive('businessSubmit', function ($log, $compile, formManagerService) {
    return {
        restrict: 'AE',
        controller: 'BrunchesCtrl',
        link: function (scope, element, attrs, controller) {
            formManagerService.init();
            var hasError;

            element.on('click', function (e) {
                e.preventDefault();
                $log.info("brunches: \n");
                $log.info(scope.brunches);
            });
        }
    };
});

Here is an HTML snippet:

<!DOCTYPE html>

The above code generates a list of items in AngularJS using directives and controllers. It also includes functionalities like adding new items and saving data. Feel free to check out the plunker link for a full view of the code.

If you need any assistance or clarification, please let me know.

Answer №1

There are a few issues that need to be addressed in your code.

To start, the ng-model for the <input> is currently set to address, but you actually want it to be bound to an object called brunch which has an address property. It's important to note that each repeated item created by ng-repeat will have its own child scope.

<input data-ng-model="brunch.address"/>

Additionally, you are assigning the parent controller to a directive. Keep in mind that controllers act as singletons, so using the same controller multiple times will result in separate instances. Therefore, nesting the parent controller within a directive doesn't serve a purpose.

Check out this DEMO- [ng-model] fix

If you wish to share data across different controllers, consider setting up a service that holds the brunches data and injecting it into the relevant controllers that require access.

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

Is it feasible to incorporate a third-party JavaScript file into a React application?

I have a JavaScript file from a previous MVC project that generates a basic table using ExtJS. Currently, I'm working on developing a new React application with a navigation bar and sidebar. My goal is to explore the possibility of importing the exis ...

Strange JSON format detected when consuming the Python Hug REST API in a .NET environment

When using a Hug REST endpoint to consume JSON in .net, there are issues with embedded characters that I am facing. See the example below for a complete failure. Any assistance would be greatly appreciated. Python @hug.post('/test') def test(re ...

Utilizing unique layouts for specific views in sails.js and angular.js

I am currently working on a Sails.js + Angular.js project with a single layout. However, I have come across different HTML files that have a completely different layout compared to the one I am using. The layout file I am currently using is the default la ...

Working with JSON object values in a Spring Boot application

Here is a sample JSON data: [{"state":"Completed","mignum":146289,"projectleader":"Eric Lok","productiondate":"Jun 6, 2018","installationtiers":"Windows Server","targetplatform":"Production","apprelated":"UPS Pickup Point Web Application","appversion":"2. ...

Add the information to the current JSON file

I'm currently working with an existing JSON file and attempting to add a string into it. However, whenever I write to the JSON file, the new line characters disappear and the formatting gets altered. Check out the code snippet below: #!/usr/bin/pyth ...

Whenever I try to import a function, I encounter the error message "no exported member."

I am facing an issue with my node/typescript application where I am attempting to import a function from another file. In order to export it, I utilized exports.coolFunc = coolFunc, and for importing, I used import {coolFunc} from '../controller/coolS ...

Use Jquery to add unique styles to specific words within a paragraph

I am looking to specifically style a particular word within a dynamic div for example, <div id="info">{$info}</div> prints <p>here you can get info about somnething. if you want more info about something then click here....</p> ...

Rendering React Router server-side with client-side session information

Currently, I am working with mozilla client-sessions in conjunction with express/node. My goal is to pass my session.user to the react-router within a standard * request. Despite my efforts and attempts, I keep encountering an issue where it becomes unde ...

The <form> element is giving me headaches in my JavaScript code

Trying to troubleshoot why my HTML pages render twice when I add a form with JavaScript. It seems like the page displays once with the script and again without it. Below is the basic HTML code: <form action="test.php" method="post"> <div class=" ...

Using Ajax to insert data into WordPress

Looking to incorporate data into the WordPress database using Ajax integration. functions.php function addDataToDB(){ global $wpdb, $count; $count = 25; $wpdb->insert( 'custom_table', array( 'slid ...

AngularJS will redirect to the specified URL and then trigger a function

One issue I've encountered is with my parent controller and child controllers in the app. There are times when I need to redirect the user to a different route URL and then call a function within that URL's controller. <div ng-controller=" ...

What is the best way to maintain an ongoing sum of multiple values using bacon.js?

Experimenting with the power of bacon.js. I want to maintain a dynamic total of values from a set of text inputs. The example on the github page utilizes the .scan method along with an adding function, which functions well for simple increment and decremen ...

When it comes to E2E testing with an Angular, Python, and MongoDB web stack, which tool is more effective: Selenium or Protractor?

Just discovered the protractor framework, which offers end-to-end testing for Angular applications. I'm curious to know which test framework is more suitable for the webstack I am using - Angular, Python, and MongoDB. Should I go with Selenium or Pro ...

Is it possible that the method of wrapping options using an array is not functioning correctly in the quiz app being managed in React?

I need your help in figuring out where I've made a mistake. The following line is causing an error: const choices = Array.forms(document.querySelectorAll('.choice')); console.log(choices); ...

How to increment a date by 1 in an AngularJS function

I have a table with 5 cells in the header, each representing a different week (for example: Week 01, Week 02, and so on). In the first cell, the week is displayed like this: <div class="monthCells">Week {{vm.selectedPeriod}}</div> and it sho ...

What is the most efficient method for transferring rows from an SQL Database to JavaScript?

Recently, I've been exploring the dynamic features of HTML5 IndexedDB controlled by Javascript and how to sync it with an SQL Server database for offline access. The challenge I'm facing is determining the most efficient method to transfer data ...

Exploring Protractor functionality by testing ui-bootstrap-alert with the dismiss-on-timeout attribute

When running my protractor test, I encountered an issue where an alert is displayed when an error occurs in the app. Here is a snippet of the relevant HTML: <uib-alert type="danger" dismiss-on-timeout="5000" close="closeAlert()"> <span>Err ...

Ensure Angular JS includes a space or special character after applying a currency filter

Is there a way to include a space or special character after the "₹" symbol? Desired output: ₹ 49 Current output: ₹49 HTML - {{cart.getTotalPrice() | currency:"₹"}} ...

Tips for effectively utilizing Formik's handleChange method multiple times to update a single value

Utilizing Material-UI along with Formik, I am trying to enable two input fields to modify a single value. The scenario involves having a TextField and a Slider where both inputs should have the ability to change the value for period. When assigning the sam ...

Using JavaScript to listen for events on all dynamically created li elements

Recently, I've created a simple script that dynamically adds "li" elements to a "ul" and assigns them a specific class. However, I now want to modify the class of an "li" item when a click event occurs. Here's the HTML structure: <form class ...