Is it possible to inject local variables into a controller defined with ng-controller directive?

Is there a way to utilize myCtrl instead of myCtrl2 in the given example, passing an argument as a local variable rather than attached to $scope?

The $controller service is capable of performing the necessary operation to encapsulate an existing controller, however, it cannot be accessed directly from the template.

<div ng-app>

  <script type="text/ng-template" id="/tpl.html">
    value of y: {{y}}
  </script>

  <div 
    ng-repeat='x in [1,2,3]' 
    ng-controller='myCtrl2'
    ng-include="'/tpl.html'">
  </div>

</div>
function myCtrl($scope, x){
  $scope.y = x * 20;
}

function myCtrl2($scope){
  $scope.y = $scope.x * 20;
}

http://jsfiddle.net/4Zmym/16/

Answer №1

It's not completely clear from your inquiry what exactly you're seeking, but a possible solution could be creating a custom directive (based on the ngController directive) that allows for specifying controller injectables:

app.directive('myController', function($controller) {
  return {
    scope: true,
    link: function(scope, elem, attrs) {
      var locals = scope.$eval(attrs.locals);
      angular.extend(locals, {$scope: scope});
      $controller(attrs.myController, locals);
    }
  };
});

You can implement it like this:

<div my-controller='MainController' locals='{x: "test", y: 42}'></div>

Check out this JsFiddle example showcasing the technique: http://jsfiddle.net/BinaryMuse/qBZZk/

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

Regular expressions: understanding greedy versus lazy quantifiers

Imagine this situation: a = 'one\\two\\three.txt'; The desired output is "three.txt". However, the attempted solution of: a.match(/\\(.+?)$/) is unsuccessful. What could be causing this issue? How can we successf ...

Hey there, I'm looking to use different CSS fonts on Windows and Mac for the same page on a web application. Can someone please guide me on how to accomplish this?

In order to tailor the font based on the operating system, the following criteria should be followed: For Windows: "Segoe UI" For Mac: "SF Pro" Attempts have been made using the code provided below, but it seems to load before the DOM and lacks persisten ...

Retrieving JSON parameters using $http.get in Angular from one URL and then from another source

As a newcomer to Angular, I am working on setting up basic UI components. I have successfully set up a RESTful Spring service and tested it using curl like this: curl http://myPersonalSite.com:1313/service/event?id=1 This command returns a JSON response ...

What is the URL I need to visit in my browser to monitor updates while running npm?

I am interested in utilizing npm to monitor any changes made in my project and immediately view them in my browser. Essentially, I have been implementing npm using this modified code snippet from this source, which allows me to run the command npm run buil ...

Is it possible to bind a function to data in Vue js?

Can a function be data bound in Vue? In my template, I am trying something like this: <title> {{nameofFunction()}}</title> However, when I run it, it simply displays 'native function' on the page. Any insights would be appreciated ...

React component encounters rendering issue with if-else statement

I'm attempting to use an if-else statement to check if the photo property contains an item, but for some reason, the code below is not working as expected. I can't seem to figure out what's wrong with it. Everything appears to be correct in ...

Creating a smooth sliding textarea in HTML

I am working on creating an HTML table with numerous text input areas (textarea) that expand downwards when clicked. Currently, the textarea element expands properly but disrupts the layout of the table. My goal is to achieve a design like this Instead o ...

Obtaining JSON data through AJAX requests from different domains may result in receiving a JSON string format

I have encountered an issue with my cross-domain AJAX call. It seems that instead of receiving a JSON object as expected, I am getting a string from the API provider. Here is the code snippet for my AJAX request. $.ajax({ async: false, ...

Retrieve the concealed method's name within the immediately invoked function expression (IIFE

This Meteor sever code has a private method called printFuncName within an IIFE. However, when this method is invoked from a public method, it results in the following error: TypeError: Cannot read property 'name' of null I am curious to unde ...

Modal opening leading to loss of event bindings on the background page

I created a webpage that has links to modals. There is a search bar named #top-search at the top of this page. I added an event in my main JavaScript file within the ready function: $('#top-search').keypress(function (e) { if (e.which ...

What is the best way to fill in references that are nested within an array object using mongoose?

How do I go about populating the product fields within the cart array provided below? { "_id": "5bbd1c6e2c48f512fcd733b4", "cart": [ { "count": 1, "_id": "5bbd30ed9417363f345b15fc", "product": "5ba93a6d ...

Using axios to make a request from a server to itself

I'm facing an issue where I am attempting to send a request from the server to the same server using axios as a PUT method. Here is an example of what I have tried: await axios({ url: `http://localhost:4000${url}`, method: requestType, ...

Determine the number of occurrences of specific values within a group of objects based on a

I have the following dataset: const data2 = [ { App: "testa.com", Name: "TEST A", Category: "HR", Employees: 7 }, { App: "testd.com", Name: "TEST D", Category: "DevOps", Employee ...

Filtering Data in a Drop Down Menu with AngularJS

So I've got some data in a dropdown like this: [{Item:'1'},{Item:'2'},{Item:'3'},{Item:'4'},{Item5:'5'}] My challenge is to create 7 dropdown lists, and each one should only display a specific item. ...

Generate a dynamic tooltip for a specific element

My goal is to display a tooltip when a user selects specific text on the page - similar to annotating text. I have successfully created a v-tooltip component dynamically. I managed to select the element in JavaScript, but I am struggling to wrap it with t ...

React: Actions should only be simple objects

My project structure is set up as follows: https://i.sstatic.net/f1wdV.png In GlobalStore.js, I have the following code: import React from 'react' const GlobalContext=React.createContext(); const GlobalProvider=GlobalContext.Provider; const Gl ...

Guide to extracting HTML content from an AJAX call?

I am currently attempting to extract a value from an HTML form. This involves making a GET request to a specific URL, retrieving the HTML content, and then utilizing jQuery to parse through it. Below is the snippet of HTML that I need to navigate through: ...

"Encountered difficulty in retrieving the width of an element upon refreshing the

I have come across a puzzling situation with my code that involves determining the width of a block element. Here is an excerpt from the code snippet: //get the largest block: if no block, apply to first block var previous = $('.block-grid .block-gr ...

Leverage Express.js route variables for universal access

I'm currently working on integrating the Spotify API with my express.js server and facing a challenge in accessing an Authorization code from a URL parameter. I've managed to retrieve this value using let code = req.query.code within the callback ...

Changing Images with Button Click in Javascript

I am facing an issue with my buttons that should swap images once clicked. The first two buttons work perfectly, but for the third and fourth buttons, the images do not disappear when clicking another button. Below is the current code in the document head ...