Exploring the functionality of Angular directives for bidirectional data binding with object references

In my custom Angular directive (v1.4.3), I am passing two bindings.

  1. The first binding is an Object with 2-way binding (model: '=') that can either be an Array or a single Object like [{something: 'foo'}, {something: 'moo'}, ...] or just {something: 'foo', other: 'test'}
  2. The second binding is a look-up for the model in that Object (lookUp: '@'). It is a string that specifies the path to locate the desired data within the directive. For example, '[0].something' or '.something'.

I have implemented a function to retrieve the data based on the provided string, but it causes the 2-way binding to break because any updates made to the extracted data are not reflected in the original model Object.

The function I am using to extract data with a string key is:

Object.resolve = function (path, obj, safe) {
  return path.split('.').reduce(function (prev, curr) {
    return !safe ? prev[curr] : (prev ? prev[curr] : undefined)
  }, obj || self)
}

vm.data = Object.resolve(vm.lookUp, vm.model); // retrieves the necessary data for display and editing but disrupts the binding to vm.model

Is there a more Angular-friendly approach to achieve this while maintaining the binding?

Answer №1

  1. There is already a function called $parse that can be used to retrieve object properties.
  2. To maintain bindings, you can make use of $watch.
app.directive('test', function($parse) {
  return {
    restrict : 'E',
    scope : {
      model : '=',
      lookUp : '@'
    },
    template : 'The result is : {{result}}',
    link : function(scope, elem, attrs) {
      function getResult() {
        return $parse('model' + scope.lookUp)(scope);
      }  
      scope.$watch(getResult, function() {
        scope.result = getResult();
      });
    }
  }
})

http://plnkr.co/edit/J5vlnGkHfwNYDZHO4lx6?p=preview

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

What is the most efficient method for encoding and decoding extensive volumes of data for a JavaScript user?

Currently, I am in the process of developing a standalone Javascript application using Spine and Node.js to create an interactive 'number property' explorer. This application allows users to select any number and discover its various properties s ...

Whenever I click on <a href="whatever.aspx"></a>, I would like the page to be displayed within the current page

This is the code I am working with: <asp:DataList ID="dlGallery" runat="server" RepeatLayout="Flow" Width="100%" CellPadding="4" ForeColor="#333333"> <AlternatingItemStyle BackColor="White" ForeColor="#284775" /> <FooterStyle BackColor ...

Using NextJS getServerSideProps to Transfer Data to Page Component

Having trouble with my JavaScript/NextJS code, and not being an expert in these technologies. I'm using the method export const getServerSideProps: GetServerSideProps = async () => {} to fetch data from an integrated API within NextJS. The code mig ...

Angular renders HTML elements

Greetings! I am currently experimenting with using AngularJS for the frontend and Wordpress as the backend of my project. To load content from Wordpress into Angular, I am utilizing a JSON wordpress plugin along with making $http requests. The content th ...

jQuery's find method returns a null value

During my Ajax POST request, I encountered an issue where I wanted to replace the current div with the one received from a successful Ajax call: var dom; var target; $.ajax({ type: "POST", url: "http://127.0.0.1/participants", data: "actio ...

I require the ability to imprint an image using jquery

Can someone assist me with adding an ID to a cloned image using Jquery? I have almost completed the code but I am facing issues defining the ID for the cloned image. Below is the code I have written: //Make element click $(".drag").click(functi ...

Docusaurus font loading specifically optimized for body text, excluding headings

I've added the following CSS code to my Docusaurus custom stylesheet: @import url("https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500;1,600;1,700&display=swap"); :root { --ifm-color- ...

Deciphering the Results of AngularJS

What sets 'template' apart from 'templateUrl' in AngularJS directive? index.html: <!DOCTYPE html> <html lang="en" ng-app="app"> <head> <meta charset="utf-8"> <title>Index</title> </he ...

What are the steps to installing and utilizing the Chart.js package on your local machine?

I thought installing chart.js on my Raspberry Pi would be a simple task, but I seem to be struggling with it. Due to the nature of my project, I need to have it installed locally rather than relying on an online version. Following the usual steps, I navig ...

Next step is to retrieve previous store information

As a newcomer to the world of Javascript and Reactjs, I encountered an issue while attempting to execute multiple actions upon clicking a button. The first action successfully updates the store data, however, the second action seems to be using the old sto ...

Guide on building a "like" button using a Node.js Express application

I am in the process of developing a website using node, express, and mongodb. I am facing an issue with passing a variable value from my ejs file to the server side. Can someone help me solve this problem? Here is what I have attempted so far: Example Ht ...

Integrating Dialogflow with a Heroku JavaScript application

After extensive research, I delved into the realm of integrating DialogFlow requests with a webhook hosted on platforms like Heroku. With both Heroku and nodeJS impeccably installed on my system, I diligently followed the heroku tutorial to kickstart the p ...

JavaScript: The power of nested array manipulation

I'm having trouble extracting data from a parsed JSON array obtained from a shipping company. Specifically, I am attempting to retrieve the short_name of Cleveland, OH, but all my attempts to access this information have been unsuccessful. When I use: ...

What are the steps for retrieving data on the server side by utilizing a token stored in localStorage?

Currently, I am diving into the official documentation for Next.js and utilizing the App router. On the data fetching patterns page, it explicitly states: Whenever possible, we recommend fetching data on the server To adhere to this recommendation, I cr ...

"Modifying the height of an SVG <g> element: A step-by

Is there a way to adjust the height of a g element? Trying to set the height using {params} but it's not responding I made some changes in the comments because the svg is quite large (Scene.js) {/* Transformation */} <g transform="trans ...

Configuring vue-jest: Does anyone know how to set up aliases for template/script src attributes in Vue?

Dependencies: "@vue/cli-plugin-unit-jest": "^4.5.13", "@vue/test-utils": "^1.2.1", "vue-jest": "^3.0.7" I am dealing with an application that utilizes an alias (referred to as "foo") de ...

Using a three.js texture with a JSON object

Currently, I am working on a customization project where I am using three.js to export an HTML5 canvas as a 3D preview. My goal is to have the texture placed only on the front side, but it seems to appear on all sides instead. This is the code I am using: ...

Get the game using electron / determine the game's version via electron

I'm currently working on creating a game launcher using electron. There are two main questions that I have: What is the best method for downloading files from the client (specifically in AngularJS)? FTP or HTTP? How can I implement a system to detect ...

Is there a Node template engine similar to EJS that seamlessly integrates with HTML templates?

Is there a template engine for NodeJS similar to EJS that doesn't alter the original HTML template structure with its use of parentheses? In EJS, one might utilize the following code snippet to embed specific data into the HTML template: <script& ...

Discovering if an input field is read-only or not can be achieved by using Selenium WebDriver along with Java

Currently, I am utilizing selenium webdriver along with Java to create a script. One issue we are encountering is that certain fields become disabled after clicking on a button. We need to determine if these fields are transitioning into readonly mode or ...