Leveraging $scope methods from a separate controller within AngularJS

I want to transfer the $scope functions from one controller to another controller, specifically for an AngularUI dialog.

In this scenario, I need $scope.scopeVar to be accessible in PopupCtrl.

Check out this Plunkr

Solve the code as per mlarcher's comment here

main.js

angular.module('MyApp', ['ui.bootstrap']);

var MainCtrl = ['$scope', '$dialog', '$rootScope', function($scope, $dialog, $rootScope) {

  $scope.myTestVar = "hello";

  $scope.myOpts = {
    backdrop: true,
    keyboard: true,
    backdropClick: true,
    resolve: { MainCtrl: function() { return MainCtrl; }},
    templateUrl: 'myPopup.html',
    controller: 'PopupCtrl'
  };

  $scope.scopeVar = 'scope var string that should appear in both index.html and myPopup.html.';
  $rootScope.rootScopeVar = "rootScope var string that should appear in both index.html and myPopup.html.";

  $scope.openDialog = function() {

    var d = $dialog.dialog($scope.myOpts);

    d.open().then(function() {
      $scope.scopeVar = 'scope var string should be changed after closing the popup the first time.';
      $rootScope.rootScopeVar = 'rootScope var string should be changed after closing the popup the first time.';
    });
  };
}];



var PopupCtrl = ['$scope', 'dialog', 'MainCtrl', function ($scope, dialog, MainCtrl) {

   var key;

   for (key in MainCtrl) {
     $scope[key] = MainCtrl[key];
   }

   $scope.close = function(){
     dialog.close();
   }
 }];

index.html

<!DOCTYPE html>
<html ng-app="MyApp">

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f7969990829b9685d99d84b7c6d9c6d9c2">[email protected]</a>" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d3824602f2222393e393f2c3d0d7d637e637d">[email protected]</a>" data-semver="0.3.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.3.0.min.js"></script>
    <script src="script.js"></script>
    <link data-require="bootstrap-css@*" data-semver="2.3.2" rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" />
    <link rel="stylesheet" href="style.css" />
  </head>

  <body ng-controller="MainCtrl">
    <h4>{{scopeVar}}</h4>
    <h4>{{rootScopeVar}}</h4>
    <br>
    <button class="btn btn-primary" type="button" data-ng-click="openDialog()" >Popup</button>
  </body>

</html>

myPopup.html

<div class="modal-body">
   <h4>{{scopeVar}}</h4>
   <h4>{{rootScopeVar}}</h4>
</div>
<div class="modal-footer">
   <button data-ng-click="close()" class="btn btn-large popupLarge" >Close</button>
</div>

Answer №1

If you're faced with a decision, consider the following options:

  1. One choice is to utilize the scope property, which can be accessed throughout controllers by attaching it to the rootScope. For example, you can do this by setting:

    $rootScope.scopeVar = "Data that will be available across controllers";
    However, it's worth noting that this approach is not recommended - see Common Pitfalls for more information.

  2. Another option is to consider using Services. Services are ideal for reusing functionality or data.

In your specific scenario, creating a service to store, update, and share data among components could be beneficial. You can refer to this answer for a detailed explanation.

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

Dependencies in Scala.js for CSS styling

I am currently having an issue implementing Scala.js with the bootstrap library. Including the js file was a simple and straightforward process: jsDependencies +="org.webjars" % "bootstrap" % "3.3.7-1" / "bootstrap.js" minified "bootstrap.min.js" However ...

Pass KeyEventArgs object to JavaScript function

Is it possible to pass keydown events as parameters to a JavaScript function in Silverlight4? ...

Incorporating an express server into the vue-webpack-boilerplate for enhanced functionality

Recently, I got my hands on the vue-webpack-boilerplate from GitHub, and so far, it seems pretty impressive! This is my first time working with webpack and ESlint, so I'm eager to learn more. However, I have a question about integrating an express ba ...

finding the source file or code where a particular html element is being generated

In the HTML file I have, there are multiple JavaScript files added. Whenever I run the HTML file, a title tag is automatically created in my HTML file. I do not want this title tag to appear in my HTML file. How can I prevent this from happening? Or how c ...

Is it possible to deactivate the onclick event following a successful ajax request?

I am looking to disable the onclick event after a successful ajax request. <div class="report_button" id="report_button" title="Reportthis" style="width:65px;height:15px;" onclick="reported_text(user_id,lead_id);">Report</div> This is the div ...

Is it not possible to use array splice with a string that is in array format (i.e., split string

Why doesn't array splice work with a string that has been formatted into an array using the split() method? function _formatText(text) { var textList = text.replace(/\s+/g, ",").split(","); return textList.splice(1, 0, "<br />").join ...

Error: The index $_GET[...] is not defined

When transferring a javascript variable to a php file, I encounter an issue where $_GET['something'] keeps returning as an undefined index. Despite this error, the correct result is displayed and written into the xml. However, when I attempt to ...

What is the most efficient way to retrieve the key at a specific index within a JavaScript map object?

If I have the map object shown below: const items = new Map([['item1','A'], ['item2','B'], ['item3', 'C']]) I am trying to retrieve the key at index 2. Is there a method other than using a for ...

What is the best way to add all the items from an array to a div element?

I am currently facing an issue where only the last object in my array is being added to my div using the code below. How can I modify it to add all objects from the array to my div? ajaxHelper.processRequest((response: Array<Vehicle.Vehicle>) ...

Display options through numerical selection

I have been attempting to construct something, but I'm encountering difficulties. My goal is to create a functionality where entering a number in an input field will generate that many additional input fields. I've attempted to implement this us ...

Dealing with Redis session management in the event of a database disconnection

Having trouble with losing connection to Redis, which is used for sessions in my Express App. var RedisStore = require('connect-redis')(express); sessionStore = new RedisStore(config.db.redis.connection); sessionStore.client.on('error' ...

Having trouble understanding why the other parts of my header are not displaying

<head> This special function runs when the webpage is loaded. <body onload="myOnload()"> A distinctive div at the top with a unique graphic <div id="header"> <img src="resumeheader.png" alt="Header" style="width:750px;h ...

The .map() function is failing to produce a new array when utilizing the return function

For a React challenge, I was tasked with creating a card that generates a specific number of random numbers based on user input. To achieve this, I wrote a function called "getRandomNum" to generate random numbers within a given range and check if they a ...

Choose all the checkboxes that use Knockout JS

Struggling with implementing a "select all" checkbox feature as a Junior developer on a complex project utilizing knockout.Js and Typescript. I can't seem to figure out how to select all existing checkboxes. Here is the HTML: <td> <inp ...

Is there a way to dynamically import images in Next JS without having to place them in the public folder?

Currently, I am developing a textbook website in which authors contribute textbook folders containing markdown files and images: textbooks ├───textbook-1 │ ├───images │ └───markdown-files └───textbook-2 ├── ...

Using $.getJSON is not functioning properly, but including the JSON object directly within the script is effective

I'm currently working on dynamically creating a simple select element where an object's property serves as the option, based on specific constraints. Everything is functioning properly when my JSON data is part of the script. FIDDLE The follow ...

Sidebar navigation text shifting during transition

I attempted to modify the CSS and JavaScript, but unfortunately, it had no effect and actually caused more issues. I adjusted the position and display properties in the CSS, but it seems that wasn't the root of the problem. If anyone could offer assis ...

Is the injector giving back a value of undefined?

Having an issue with my legacy code where injector() is returning undefined. Check out this plnkr for more details. Furthermore, I am wondering if updating a property value in the service will automatically reflect in the scope without needing to use ...

Comparing strings in AngularJS

Struggling to compare two strings in AngularJS, I've come across various examples online. From what I understand, there are different methods like angular.equals(str1, str2), ===, and == if you're certain both are strings... Despite trying all t ...

Exploring the ng-repeat function with a Jasmine test case to determine the total sum

Can someone assist me in creating a test case for a function that calculates the total cost of items in a shopping cart? Here is my HTML code: <table> <tr ng-repeat="x in countrynames"> <td>{{x.Goods} ...