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

Guidelines for utilizing recursion in order to calculate the sum of specified values within a multidimensional array

I am dealing with a complex object data that resembles the structure provided below. My objective is to calculate the total direct package values for the top users, or "parents" compute the combined nested indirect package values from the subtree of "ch ...

Executing a single Function within the UseEffect Hook

Can anyone assist me with solving this code puzzle? I have a carousel element that includes icons for moving to the previous and next slides. Whenever these icons are clicked, a specific function needs to be triggered within the useEffect() hook. The spec ...

The automatic refresh feature of the DataTable every 30 seconds is malfunctioning

Currently, I am implementing an application that retrieves records from a database and populates them into a dataTable using JSON. Although my app is functioning correctly, I want to refresh the table every 30 seconds and update any added or modified rows ...

Using an array to dynamically input latitude and longitude into a weather API call in PHP

I am currently working on a leaflet map project that showcases the top 10 cities in a selected country. The markers are added dynamically based on the coordinates provided in the $latLng array. For example, when Australia is chosen from the select field, t ...

Issue encountered with Google charts due to JSON data being poorly formatted, resulting in an error stating that

I'm attempting to utilize a JSON file to generate a map using Google Charts. Here is my script code: google.charts.load('current', {'packages': ['geomap']}); google.charts.setOnLoadCallback(drawMap); function drawMap() ...

Stop the unnecessary reloading of Ajax data when navigating back using the browser's back button in Chrome and Internet Explorer

I am currently designing a website where the main page showcases the latest 10 blog entries. As I scroll down and approach the end of the last item on the screen, another set of 10 blog entries automatically load through infinite scrolling. If a user clic ...

A JavaScript or CSS file within an HTML document

I understand this may seem like a silly question. However, out of curiosity, is there a way to upload an HTML file (with a .html extension) as a JavaScript or CSS file (renamed with a .js or .css extension), specifying the type header as either HTML or js ...

Encountering a problem involving the apostrophe character "'" when trying to save content into a MySQL database

I have been developing an application that allows users to create HTML templates and save them. Users can utilize different components such as text, images, etc. to build HTML pages. Challenge: The issue I'm encountering is when a user inputs text wi ...

Encountering a duplicate key error in ExpressJS collection

Whenever I try to create a new event with categories that already exist in my database, such as creating an event with the category "javascript" and then attempting to create another event with categories "javascript, html, css", I encounter the error mess ...

Do these exports serve the same purpose?

Can someone help me understand why one export works while the other doesn't? I've tried to figure it out on my own but I'm stuck. Functioning Example const dataStore = new Vapi({ baseURL: 'http://domain.test/api', state: ...

What are the different kinds of properties that can be used in Vue.js

When working with Javascript, I can create arrays that hold different types of data elements like: var ex = ['name', 12, true]; console.log(ex); In Vue JS, when defining props for a component within a single file template, I have the option to ...

deciphering JSON objects based on specific keys

Struggling to complete a seemingly straightforward task has left me feeling frustrated. In the header of my HTML page, I have an external car dealer API being called. At the bottom of the page, there is another external .js file containing a series of if- ...

What options do I have for personalizing this Google Bar Graph?

I am currently working on creating a Google bar chart. You can view my progress here: http://jsfiddle.net/nGvdB/ Although I have carefully reviewed the Google Bar Chart documentation available here, I am struggling to customize the chart to my needs. Spec ...

Having trouble showing a specific number of JSON data items in SwiftUI

I am currently utilizing the SwiftUI framework and fetching JSON data from an Online API. After successfully decoding the data, I find myself facing a challenge in displaying only 6 random items from the decoded data. The requirement is to show these 6 ite ...

Where should Babel and Webpack be placed in your package.json file - under devDependencies or Dependencies?

I'm a beginner when it comes to npm and I have doubts on what should be included in dependencies as opposed to devDependencies. I understand that testing libraries belong in dev, but what about tools like babel and webpack? Should they also be categor ...

Error: Issue transferring data to controller from Ng-Style

Currently, I am developing an application using Ionic and AngularJS. In this project, I am using ng-repeat to populate the results and want to display different colors based on certain criteria. Initially, I managed to achieve this using inline ng-style c ...

Ways to populate dynamic choices for multiple Select boxes within an ng-repeat loop

When I click the "Add Row" button on an Html form, dynamic rows are added. Each row contains a 'Country' select and a 'State' select. The issue I am facing is that when I select a country in one row, all other row values change as well. ...

What is the process for sending an HTTP request within the Dialogflow -> Fulfillment environment?

When it comes to interacting with the API of my website to rectify the response for Google Assistant, I am facing some difficulties. 'use strict'; var requestNode = require('request'); const functions = require('firebase-function ...

Authentication in Feathers JS without the need for email addresses

Currently, I am in need of an authentication system for my dApp that operates without using email addresses or storing any user information. What I require is an endpoint where users can submit a seed phrase and password to generate a JWT. The process shou ...

What is the process for retrieving JSON data from a public API endpoint?

As I dive into testing a REST API for my current project, I find myself pondering the best way to access and test the API data. Can I retrieve JSON data from a public URL for testing purposes? This is a question that continues to challenge me! ...