Sharing AngularJs controllers between different modules can help streamline your

I'm facing an issue with trying to access an array from one controller in another controller. Despite simplifying the code for clarity, I still can't seem to make it work.

Here is my first controller:

app.controller('mycont1', ['$scope','$timeout', function($scope, $timeout) {

var my;

my = ['1', 'something', ......];

}]);

And here is my second controller inside a directive:

.....,controller: function($scope) {

   var m = my[0]; //I want to retrieve the array from the first controller..

}

When I attempt to call it, the array cannot be found. How can I properly utilize this array from another controller?

Answer №1

If you're looking to exchange data between controllers, consider creating a shared service that they both rely on.

HTML:

<div ng-app="app">
    <p ng-controller="controller1">{{message}}</p>
    <p ng-controller="controller2">{{message}}</p>    
</div>

JavaScript:

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

app.service('dataService', function() {
    return {
        message: 'Hello world!'
    };
}).controller('controller1', function($scope, dataService) {
    $scope.message = dataService.message;
}).controller('controller2', function($scope, dataService) {
    $scope.message = dataService.message;
});

See it in action here: https://jsfiddle.net/ben1729/yeLd9rnb/3/

Answer №2

If your project is on the smaller side, consider utilizing only $rootScope for functionality.

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

PHP response triggers AJAX autocomplete functionality in JavaScript

The autocomplete hints are not displaying any response for me. Here is the jQuery code that I am using: jQuery( ".newtag_new" ).autocomplete({ minLength: 0, source: function( request, response ) { jQuery.ajax({ type: 'GET ...

Switch the div class when clicked, and revert it when the body is clicked

Allow me to elaborate on the issue: I currently have <div class="contact"> <div id="form"></div> <div id="icon"></div> </div> My goal is to change the class of .contact to .contactexpand (or simply ...

Angularjs: I am trying to assign a value to automatically bind to my Checkbox if it remains untouched or unchecked

I'm facing a minor issue. How can I assign a default value to a checkbox's ng-model? For instance, consider the following scenario <input type="checkbox" ng-model="data.data" ng-value="yes" /> ready? What I want is to set the value to "No ...

JavaScript: a highly effective method for verifying if a variable is a function, an array, or an object

Imagine a scenario where we have a variable that could potentially be a function, object, or array. I am in search of the most efficient method to determine its type. In my opinion, the current approach is not optimized because if I already know that isF ...

Encountering a strange issue when attempting to link app.js with mongodb

I recently set up MongoDB and the Compass, everything was working fine until I tried to connect MongoDB with my app.js. Now I'm getting a strange error message. Could anyone help me understand what this error means and how I can fix it? Unfortunately, ...

Adjusting the settimeout delay time during its execution

Is there a way to adjust the setTimeout delay time while it is already running? I tried using debounceTime() as an alternative, but I would like to modify the existing delay time instead of creating a new one. In the code snippet provided, the delay is se ...

Transferring Information from Angular Interface to NodeJS through a JSON Document

I am currently working on establishing a connection between an AngularJS front end and a NodeJS back end application. The main objective is to manipulate data in a JSON file instead of a traditional database. I have attempted to set up the post method on ...

Issues with the Content Editable Functionality

While working on my website, I encountered a strange issue. For some reason, I can't seem to get the contenteditable="true" attribute to work on the heading with the ID "hl". It would be awesome if someone could help me figure out how to mak ...

I am looking for a way to display or conceal text depending on the presence of an image

Could you please help me with this? I am looking for a solution where text is displayed only when there is content in the src attribute of an img tag. Essentially, I need JavaScript code that can identify if an attribute has content and then make a paragra ...

Transitioning from one bootstrap modal to another in quick succession may lead to unexpected scrolling problems

I'm facing a challenge with two modals where scrolling behavior becomes problematic when transitioning from one to the other. Instead of scrolling within the modal itself, the content behind it is scrolled instead. In order to address this issue, I im ...

Using Svelte to effectively connect to a specified object within an array

Check out this code snippet: <script> let data = [ {id: 1, first: "x"}, {id: 2, second: "y"} ]; </script> <input type="text" bind:value={data.first}/> If you modify the value in the input field and ...

Using Javascript to access a website from a Windows Store application

Currently, I am working on a project to create a Windows store app using HTML and JavaScript. One of the key components of my app involves logging into a specific website with a username and password. Here is an example website for reference: The process ...

The preflight OPTIONS request for an AJAX GET from S3 using CORS fails with a 403 error

I have come across various discussions and issues related to this topic, but unfortunately, I have not been able to find a solution yet. I am attempting to use AJAX GET to retrieve a file from S3. My bucket is configured for CORS: <?xml version="1.0" e ...

Is there a better method to accomplish this task in a more effective manner?

Is there a more efficient way to achieve this code with fewer lines of code? I'm looking for a solution that avoids repetition and makes it easier to manage, especially since I plan on creating multiple instances of this. Performance is a key consider ...

transferring the value of a textbox into another textbox

I am trying to extract the value from one textbox and transfer it to another textbox. Here is my current code: <input type="text" value="Keyword" id="one" /> <input type="text" value="Search" id="two" /> <a href="#" id="btn">button</ ...

Is it possible to connect a date range picker custom directive in AngularJS with the behavior of AngularUI-Select2?

I'm currently utilizing Angular UI - Select2 directive for displaying an option box. Bootstrap Date-Range Picker for showing a date picker Both functionalities work effectively on their own. Functionality of the Date picker Whenever there is a ch ...

Is there a way for me to access the "ViewBag" value from the Controller in a JavaScript file following an Ajax response?

How can I access the ViewBag value that has been initialized in one Action method before making an Ajax call to another Action Method in my JavaScript file? Any assistance would be greatly appreciated. ...

jQuery swap- enhancing the appearance of numerical values

I am looking to customize specific characters within my <code> tag. While searching online, I came across the .replace() function but encountered issues when trying to style numbers. My goal is to change their appearance without altering the text its ...

Issue with Typescript and react-create-app integration using Express

I'm relatively new to Typescript and I decided to kickstart a project using create-react-app. However, I encountered an issue while trying to connect my project to a server using express. After creating a folder named src/server/server.ts, React auto ...

The error message "no match found" can only occur on the server-side when using jQuery version 1.x

Having an issue with this small section of code: $('.desc_container').each(function() { var fulltext = $(this).text(); if(fulltext.length > 50) { var myRegexp = /^(.{47}\w*\W)(.*?)$/g; var match = myRegexp.exec(f ...