Efficient method for transferring ng-model data to controller

I have a complex data structure in JSON that follows a hierarchical format. Additionally, I have a reusable Django template that is connected to a specific part of this structure. In order for my template to function correctly, I need to determine the exact location within the structure whenever the template is rendered. I have made progress but there's one key piece missing:

http://jsfiddle.net/trubliphone/fd64rn3y/

The issue lies in passing the current ng-model to a controller.

Below is some code excerpt (more detailed version available in the provided jsfiddle link):

my_app.js:

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

myApp.factory('$global_services', ['$http', function($http) {
  var data = {};
  $http.get("some_url", {format: "json"}) {
    /* THIS REQUEST RETURNS A BIG CHUNK OF HIERARCHICAL JSON */
    .success(function (data) {          
      data = data; 
    })
  });

  return {
    getPathFromModel: a_clever_fn_i_wrote_that_returns_a_string(),
    getModelFromPath: a_clever_fn_i_wrote_that_returns_a_model()
  }

}]);

myApp.controller('MyController', ['$scope', '$attrs', '$global_services', function( $scope, $attrs, $global_services ) {

  if ($attrs.currentModelPath) {
    /* if you passed current_model_path, get the current_model too */
    $scope.current_model_path = $attrs.currentModelPath;
    $scope.current_model = $global_services.getModelFromPath($scope.current_model_path);
  }
  else if ($attrs.currentModel) {
    /* if you passed current_model, get the current_model_path too */
    $scope.current_model = $attrs.currentModel;
    $scope.current_model_path = $global_services.getPathFromModel($scope.current_model);
  }
}]);

my_template.html:

<div ng-app="myApp">  
  <div ng-controller="MyController" current_model_path="data">
    {{current_model.name}}:
    <ul ng-repeat="child in current_model.children">
        <input type="text" ng-model="child.name"/>  {{ child.name }}        
        <!-- LOOK: HERE IS A NESTED CONTROLLER -->
        <div ng-controller="MyController" current_model="child">      
          {{current_model.name}}:
          <ul ng-repeat="child in current_model.children">
            <input type="text" ng-model="child.name"/> {{ child.name }}
          </ul>
      </div>
    </ul>
  </div>    
</div>

The challenge arises in the "div" element for the nested controller; I pass the {{child}} ng variable as an attribute, but upon receiving it, the controller interprets it simply as the string "child". How can I successfully pass the actual model object?

Thank you.

Answer №1

  <div ng-controller="MyController" ng-init="data = child">

By including this code, you are creating an object within the inner scope called data.

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

The alphaMap I'm using doesn't seem to be achieving the desired transparency in my material

I am attempting to create a chainlink surface using 2 textures. The first texture is a standard map that gives the metal links a metallic appearance against a white background (diffuse): The second texture is an alpha map: My attempt to apply both textur ...

Divider displayed between images in Internet Explorer 8

On my website, I have arranged four images in a square using the code below: <div id="tempo_main"> <div id="tempo_content"> <div style="text-align: center;z-index: 3;position: absolute;right:350px; left:350px; t ...

Scope problem leading to variable being returned as undefined

Having some trouble with fetching youtube videos for the data I scraped from officialcharts.com. Even though I can scrape the data and obtain the youtube URLs, the variable youtubeUrl is not being assigned a value when I try to push the data into the array ...

Delivering static assets through a POST request with express.js

I'm having an issue serving static content for a Facebook app using express.js app.configure(function (){ app.use('/', express.static(__dirname + '/public')); }); Everything is working fine with a GET request, but when I try ...

Using pre-built modules in an environment that does not support Node.js

Despite the limitations on node API usage (such as fs, http, net...), vanilla JS can still be used on any engine. While simple functionalities can be easily extracted from packaged modules if licensing terms are met, things get complicated when dealing wit ...

Issue with Enter key not working on an individual textbox within Javascript/PHP chat functionality

Recently, I created a chat feature with text boxes that send messages when the ENTER key is pressed. However, I encountered an issue with it not working for the "Warning" functionality. Whenever I press Enter in this context, nothing happens. Can anyone pr ...

What is the best way to dynamically insert a directive element between an already existing parent directive and its child directive?

Background: Working within the constraints of a custom CMS that limits access to the code base, I am exploring the option of using JavaScript for DOM manipulations in certain scenarios. Problem: The issue I am facing involves a container directive conta ...

The on() method in jQuery is failing to work on an element that has a class added dynamically

After adding an active class to a link once a product is added to cart, I tried using that class to determine the function of the link. However, the on() click event on the link does not trigger unless the page is reloaded. Below is the code snippet where ...

Revising Function Templates in Angular's UI Bootstrap Pagination

In my application, I am utilizing Angular UI Bootstrap for pagination. Specifically, I am interested in customizing the functions for First/Last and Previous/Next buttons. My attempt to change the function of the Last button to call "changePage" instead o ...

Tips on revealing TypeScript modules in a NodeJS environment

Currently, I am working on developing a TypeScript library. My goal is to make this library compatible with both TypeScript and JavaScript Node projects. What would be the most effective approach for achieving this? Should I create two separate versions ...

angularjs code to dynamically change the selected index of an option in a document

This code snippet demonstrates how to achieve this functionality using pure JavaScript: document.getElementById("mySelect").selectedIndex = "0" <select class="selectpicker" id="mySelect"> <option>English &nbsp;</option> < ...

Understanding the difference between the local and global locations of a three.js Object3D

Initially, I envisioned my small 'ship' with turrets that could track a target. This is the jfiddle I created to showcase it. You can view it here. However, when the turrets track, they behave strangely. I noticed that the turret seems to believe ...

AngularJS: Applying Timezone to Date Formatting

Having trouble formatting my date input to the desired timezone using angularjs 1.2.26. Here is a code example for reference: http://plnkr.co/edit/CxCqoR3Awcl1NFrCZYjx?p=preview {{'2015-07-10T12:37:08Z' | date : "MMMM d, y 'at' h:mma Z ...

Error in Express JS: Attempting to access properties of an undefined variable (reading '0'). Issue with SQL query

Struggling to insert something in my database and then access it directly after. Due to the asynchronous nature of node.js, my plan doesn't seem to work out. However, I am confident that there is a solution to make this happen. Here's the code sn ...

Node.JS program unexpectedly logging MySQL results to console and exhibiting erratic behavior

Recently, I encountered a peculiar error while working with Node.JS MySQL. Strangely, I noticed that a result was being logged in the console without any corresponding code line instructing it to do so. Even more baffling was the fact that when I intention ...

How can we use the jQuery each loop to iterate through a JSON object, compare values to another object, and ensure that no duplicate prints occur?

Hey everyone! I'm currently working on a music player and I'm utilizing JSON to store my ID3, also known as "MP3 Metadata". The issue I'm facing is that I'm extracting an object and trying to compare the values to avoid repeating the sa ...

The react-xml-parser package is asking for Babel version "^7.0.0-0", however it was instead loaded with version "6.26.3". I have already attempted all available solutions to resolve this issue

I have attempted numerous solutions from the Github community regarding this issue, but unfortunately none have worked for me. /node_modules/react-xml-parser/dist/bundle.js: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you ha ...

Effective ways to replace an image using JavaScript

I am currently working on implementing a show/hide function, but I am encountering an issue with swapping the image (bootstrap class). The show-hide function is functioning properly; however, I am struggling to determine which class is currently displayed. ...

Leveraging the powerful combination of Protractor, Appium, and SauceLabs

Trying to automate my Protractor tests against mobile has been quite a challenge. After scouring the web, I stumbled upon what seems to be the official guide for Appium with Saucelabs: I diligently followed the instructions provided and configured my co ...

What is the necessity of explicitly requesting certain core modules in Node.js?

The documentation explains that certain core modules are included in the Node.js platform itself and are specified within the source code. The terminology can get a bit confusing when it comes to details. The term "global objects" (or standard built-in obj ...