Create a dynamic property for the scope object in AngularJS

I am in the process of developing a versatile method that retrieves data from a service and populates it in a dynamic property specified within the function. The issue I am encountering is that while the value is successfully assigned to the text box using angular.element, it does not populate in the model. Below is an example of the code:

<div class="input-group">
<input class="form-control" id="ImgRollover" name="ImgRollover" ng-model="contentEntity.imgRollover" placeholder="" readonly="readonly" type="text">
<div class="input-group-btn">
    <button class="btn" type="button" ng-click="pickImage('contentEntity.imgRollover')">

    </button>
</div>

Here is a snippet of my controller method which utilizes a service returning a promise:

$scope.pickImage = function (attrModel) {
        ImageSelector.selectImage().then(
            function (value) {
                //angular.element("#" + attrModel).val(value);
                $scope[attrModel] = value;
        });
};

The 'attrModel' refers to a property name within the scope object contentEntity. However, the actual name of this property is only known dynamically through the method parameter.

Answer №1

<button class="btn" type="button" ng-click="setImage('highlight', 'imgPreview')"></button>

$scope.setImage = function (modelAttr1, modelAttr2) {
        ImageSelector.chooseImage().then(function (result) {
                $scope[modelAttr1][modelAttr2] = result;
        });
};

This solution should be effective.

Answer №2

Although there have been comprehensive responses, I wanted to create a dynamic property generator. The function below splits the attrModel by '.', then modifies the $scope by adding or returning each property based on whether it already exists or not. The last key is preserved outside of the loop for easy appending of values.

$scope.pickImage = function (attrModel) {
        ImageSelector.selectImage().then(
            function (value) {
                var parent = $scope,
                    current,
                    attribute,
                    attributes = attrModel.split('.');

                while(attributes.length > 1 &&
                      (attribute = attributes.shift()) &&
                      (current = parent[attribute] || (parent[attribute] = {}))) {

                    parent = current;
                }
                current[attributes[0]] = value;
        });
};

If you prefer doing this the Angular way, using a service could be more suitable. Here's an example:

View jsfiddle example here

angular.module('myApp').service('ObjectWalker', function () {
        var getNodeData = function (object, path) {
            var parent = object,
                current,
                attribute,
                attributes = path.split('.');

            while(attributes.length > 1 &&
                  (attribute = attributes.shift()) &&
                  (current = parent[attribute] || (parent[attribute] = {}))) {

                parent = current;
            }
            return [current, attributes[0]];
        };

        return {
            set: function(object, path, value) {
                var nodeData = getNodeData(object, path);
                nodeData[0][nodeData[1]] = value;
            },
            get: function(object, path) {
                var nodeData = getNodeData(object, path);
                return nodeData[0][nodeData[1]];
            }
        };
    })

Answer №3

Although there is already a response, I'd still like to share something regarding dynamic properties...

<!DOCTYPE html>
<html>

  <head>
    <script src="https://code.angularjs.org/1.2.23/angular.js"></script>
    <script type="text/javascript">

      var num = 0;
      function mainCtrl($scope) {

        num++;

        $scope.pickImage = function (attrModel) {
            num++;
            alert(attrModel)
            $scope[attrModel] = num;
        };

        $scope.getValue = function(attrModel) {
          return $scope[attrModel];
        }

      }

    </script>
  </head>

  <body ng-app ng-controller="mainCtrl">

      <input type="text" ng-model="example.obj" />

      <br/>
      <button ng-click="pickImage(example.obj)">Click Me</button>
      <br/>
      Display the value after button click,
      please note that there are no single quotes
      <br/>
      Value: {{ getValue(example.obj) }}


  </body>

</html>

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

Ways to disable the caching feature in Google Chrome

When I am working on CSS and JS around a page, I need to disable the cache mechanism in Google Chrome browser. A trick is to open Chrome DevTools, which automatically disables the cache mechanism (you can configure this in the settings section). Are ther ...

How can you extract and save all links on a webpage based on their class name?

Hello everyone, this is my first question on Stack Overflow. I am trying to extract all links on a page by their class name, store them in an array, and export the results as a JSON format file named results.json. My background is in PHP, C++, and I am c ...

How to extract only the value from a MongoDB query using NodeJS

Currently, I am attempting to extract just the value of a specific field from a MongoDB document using the following code: var collection = db.collection('people'); collection.find({"name" : "John" }, { phone : 1, _id : 0 }).toArray(function (e ...

Maximizing efficiency when conducting a thorough analysis of the contents within a JSON object and implementing jQuery

I am currently using an ajax call to send data to a controller and retrieve json data in return. Here is an example of the data that is returned: { "old": "The Old Password field is required.", "new": "The New Password field is required.", "n ...

Obtaining a value based on another value within an object the AngularJS approach

Is there a specific AngularJS method to retrieve a value from an object using its key? var myobj= { "set1": { "key": "B11", "color": "yellow" }, "setA": { "key": "F34", "color": ...

Create a cylindrical HTML5 canvas and place a camera view inside the cylinder

I have a unique project in mind that involves creating an HTML5 canvas cylinder with the camera view at its center. The walls of the cylinder will display images, and the entire structure should be able to rotate and zoom. If anyone has any advice on how ...

Tips for saving information from a constantly changing table into a database

I'm currently exploring options for storing data from a dynamic table into a database. Here's the scenario: I'm in the process of creating a system to manage drivers' journeys. The system will track the driver's workday, dividing ...

It seems that the Bootstrap 4 Modal Pop up window is having difficulty closing

I recently completed a project on creating a matching game. After all the cards are successfully matched and the game finishes, a congratulatory modal pops up. However, I encountered an issue where the modal would not close after clicking the "Play Again" ...

When attempting to print using React, inline styles may not be effective

<div styleName="item" key={index} style={{ backgroundColor: color[index] }}> The hex color code stored in color[index] displays correctly in web browsers, but fails to work in print preview mode. Substituting 'blue' for color[index] succe ...

Show text using AJAX when the form is submitted

I'm in the process of creating a basic form with a submit button (see below). My objective is to allow users to enter text into the input box, click submit, and have the page refresh while displaying the entered text in a div element. The user's ...

Fastblox - utilizing javascript SDK for group chatting

I've been facing issues setting up a group chat using QB Javascript SDK. There are a few problems I am encountering: Firstly, I consistently receive a "room is locked" message. Here's the link to the screenshot: https://i.sstatic.net/auR21.png. ...

Steps to fix the moment-timezone import problem on meteor npm

I've been attempting to integrate the moment-timezone npm package into my meteor app without success. While the atmosphere package works smoothly, I prefer to use the npm package since the atmosphere one is no longer being updated. I have completely r ...

Generating step definitions files automatically in cucumber javascript - How is it done?

Is there a way to automatically create step definition files from feature files? I came across a solution for .Net - the plugin called specflow for Visual Studio (check out the "Generating Step Definitions" section here). Is there something similar avail ...

Tips for modifying the font color of placeholders within md-chips?

I'm working on some code that involves an md-autocomplete element. At the moment, I am looking to modify the font color of the chip's placeholder. <md-chips flex class="md-accent" ng-model="vm.job.skills" readonly="vm.isExpi ...

Encountering an Ajax Issue with Laravel 5.4

I encountered the following error: "{"status":"error","msg":"Category was not created"}" Below is my Controller Function where I execute the action : function create_category(Request $request){ if($request->ajax()){ $c ...

Submit the form to MailChimp and then show a personalized success page

I am currently developing a MailChimp subscription form that is set to send the form $_POST data to MailChimp, without loading the success page. In other words, I aim to trigger custom JS upon submission. The code snippet below outlines my progress so fa ...

Step-by-step guide on generating multiple division elements according to the values specified by the user

Currently, I am focused on a project using asp.net. The primary objective is to create an image div whenever a button is clicked. This involves fetching the image from a database and displaying it on the screen, either in another div or table. I would ap ...

Display and conceal div with jQuery dropdown

I have limited knowledge of javascript, but I am attempting to implement the following code which is functioning properly. However, I am encountering an issue when I try to add a "..." or ":" at the end of the "Choose" option, causing the code to stop work ...

Upon reloading, the dynamically generated table does not appear accurately

When a table is dynamically created using JavaScript/jQuery/html from an Ajax call, it initially displays correctly formatted. However, upon refresh/reload, the formatting of the table becomes incorrect. To address this issue, I have implemented a Promise ...

Synchronous AJAX calls in jQuery

My system needs to handle up to 180 IO-intensive AJAX jobs on the server side, involving long running SELECT queries. To optimize CPU core usage, I want to transition from executing these AJAX calls sequentially to allowing a maximum of 4 parallel request ...