Proper method for accessing the scope from a directive across several controllers

I have a directive called add-tags that I intend to use in various areas of the application. It is used to add tags to an array and then save them from the main controller. The user can edit the list when previewing on a different view or controller (modal). On the main page, I include:

<add-tags tags="tags"></add-tags>

Here is how my directive is set up:

'use strict';

        angular.module('theApp')
            .directive('addTags', function() {
                return {
                    templateUrl: 'components/add-tags/add-tags.html',
                    //restrict: 'EA',
                    scope: {
                       tags:'='
                     },
                    link: function($scope, $element, attrs) {
                    } //link
                };
            });

How can I access previous tag data from the edit controller? When I use,

<add-tags tags="workDetails.tags"></add-tags>

The entire data disappears from the scope, but if I do this instead:

<span ng-repeat="x in workDetails.tags">
           <h1>{{x.name}}</h1>
        </span>

I am able to see the list of tags. Any assistance would be greatly appreciated :)

Below is an example of the add-tags.html file:

<div ng-repeat="tag in tags" class="text-center new-item">
            <div class="input-group">
                <input type="text" name="" class="form-control" ng-model="tag.name">
                <span class="input-group-btn">
                    <button 
                       type="button" 
                       class="btn btn-default"
                       ng-click="deleteTag($index)">
                       Delete
                    </button>
                </span> <!-- /.input-group-btn -->
            </div> <!-- /.input-group -->
        </div>

        <div class="form-group" ng-hide="tags.length == tags_max">
            <input type="text" class="form-control" placeholder="Enter tag:" ng-model="tag">
        </div> 

        <!-- /.form-group -->
        <button 
            type="button" 
            class="btn btn-primary center-block"
            ng-disabled="tags.length == tags_max"
            ng-class="{ 'btn-danger': tags.length == tags_max}"
            ng-click="addTag()">
            Add tag
        </button>

        <hr>

Answer №1

The code provided is correct and there doesn't seem to be any issues with it. However, it seems like you might be assuming that the "workDetails" object should be globally accessible. To make your scenario work, you might need to create a "workDetailsService" that manages the tag state.

Check out this working Plunkr based on the code snippets you shared, but with a workDetailsService added for state management and routing implementation.

I introduced a service to handle the tags:

theApp.factory('workDetailsService', function() {
  return {
    tags: [{
      name: "Tag 1"
    }, {
      name: "Tag 2"
    }, {
      name: "Tag 3"
    }]
  }
});

This service was then injected into two directives, namely "listTags" and "editTags":

theApp.directive('editTags', ['workDetailsService', function(workDetailsService) {
  return {
    templateUrl: '/edit-tags.html',
    link: function($scope, $element, attrs) {

      $scope.tags_max = 4;
      $scope.tags = workDetailsService.tags;

      $scope.addTag = function() {
        workDetailsService.tags.push({
          name: $scope.tag
        })
      }
      $scope.deleteTag = function(index) {
        workDetailsService.tags.splice(index, 1)
      }
    }
  };
}]);

theApp.directive('listTags', ['workDetailsService', function(workDetailsService) {
  return {
    templateUrl: '/list-tags.html',
    link: function($scope, $element, attrs) {
      $scope.tags = workDetailsService.tags;
    }
  };
}]);

By centralizing the tags state within the service, the directives encapsulate the handling of tags instead of controllers, making them reusable across the application.

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

Sorting through a list of strings by checking for a specific character within each string

After spending years dabbling in VBA, I am now delving into Typescript. I currently have an array of binary strings Each string represents a binary number My goal is to filter the array and extract all strings that contain '1' at position X I ...

Troubleshooting: Angular post request encountering 415 error issue

I'm attempting to retrieve the response from the code snippet below, which produces a JSON output. When I try this on the server, I encounter a 415 error and do not receive the response. constructor(private http: HttpClient){} public getReports(pos ...

Module import error in THREE.js

Currently, I am attempting to bring in the threejs and GLTFLoader modules into my project. Both of these modules (just for testing purposes) are located within the same root/js/ directory. import * as THREE from './js/build/three.module.js'; // I ...

What is the best way to restrict user input to only numbers (including decimal points) in a text field?

How can a textbox be restricted to only accept valid numbers? For instance, allowing users to enter “1.25” but preventing inputs like “1.a” or “1..”. Users should not be able to type the next character that would result in an invalid number. ...

JavaScript does not reflect updates made to the ASP.Net session

After clicking the button, I trigger the JavaScript to retrieve the session information. However, I am encountering an issue where the value of the session is not being updated. alert('<%= Session["file"]%>'); ...

Controlling dynamic fields within a web page - Utilizing Postgres and MongoDB databases

My application utilizes MongoDB and PostgreSQL as databases, with AngularJS for the UI. A key requirement is the ability to dynamically add fields (columns) on pages, allowing users to define their attributes when adding these fields to the system. In add ...

Utilizing Smarty to Retrieve JavaScript Variables from Database Entries

Currently, I am working on a PrestaShop page that uses the file extension ".tpl". To enable auto complete for the javascript code, I have defined an array of currencies as shown below: var currencies = [ { value: 'Afghan afghani', data: 'AF ...

Sequelize is having trouble recognizing a valid moment.js object within the where clause

In my Sequelize query, I am facing an issue with the createdAt property in the where object: let prms = periods.map((period, index, arr) => { if (arr[index + 1]) { return sequelize.models.Result.aggregate('value', 'avg', ...

Attempting to extract data from JSON string with SQL Query and OpenJson

I have a very complex JSON string that I need to parse using SQL in order to generate a report. The JSON contains objects nested at multiple levels, and I'm seeking guidance on how to efficiently extract all the data using a single SQL query utilizing ...

Code remaining stable post-execution of promise

I'm facing a problem with my Node.js application where I'm using promise-mysql and bluebird packages to make calls to a MySQL database. Despite following tutorials and successfully querying the database, I keep encountering a timeout error. The p ...

Adjust the navigation menu to display or hide as the page is being scrolled

Implementing an offset to display/hide the navigation menu when the page is scrolled 100px. Attempted to modify from lastScroll = 0 to lastScroll = 100 but it did not work as expected. Jquery: Fiddle // Script lastScroll = 0; $(window).on('scroll&ap ...

php retrieve a value from an associative array that is stored within another array

Here is an example: $arraytest = array( key => array("test"), key2 => value2, key3 => value3); foreach ($arraytest as $key=>$val) { echo $key. "=" .$val. "<br>"; } The above code will result in: key=Array key2=value2 key3=value3 Now ...

Having trouble locating the OBJ file in your Three.js WebGL project?

I am attempting to load an obj file using Three.js, but despite following various tutorials and resources online, I am only met with a black screen and no error messages in the console. The console output from the LoadingManager indicates that the objects ...

Verification of SGX Quotes using IAS

After successfully using SGX in hardware mode to retrieve the SigRL from IAS, I encountered difficulties when attempting to perform Quote attestation through their REST API. Following the REST API interface description found here, I was able to connect to ...

Creating a standalone script using npm JS package for exporting

I'm currently utilizing the npm package manager in my latest project. Within my package.json file, I have a dependency specified: "dependencies": { "litepicker": "^2.0.11" }, The dependency is on litepicker, which i ...

arranging select options in alphabetical order

One of the questions posed to me in an interview was about sorting a select option. The options were listed as follows: <select> <option>aaa</option> <option>ccc</option> <option>ddd</option> <option>bbb< ...

Eliminate all numerical values from the array

Develop a function called remove_digits that takes in two arrays of integers. The first array consists of a series of numbers, while the second array contains individual digits. The objective is to eliminate all digits from the second array that are also p ...

Find a specific item within an object using Mongoose without utilizing array.find, array.some, or array.filter

When working with mongoose, I understand how to utilize the find method to search for array fields or nested objects within documents. However, I was wondering if it's possible to perform a find operation inside an already found mongoose object like t ...

Tips for retrieving JSON data within a snowflake stored procedure

In my Snowflake SQL stored procedure, I have a JSON object saved to a variable named json_object: {"level":1,"object":"OBJECT1","object_schema":"SCHEMA1","object_type":"TABLE"}, {" ...

Having difficulty retrieving information from a json file with jquery

Currently, my project involves fetching information from a web API into a web application using JQuery. <script src="jquery-1.11.2.js"></script> <script src="jquery-1.11.2.min.js"></script> <script type="text/javascript"> $( ...