admin管理员组

文章数量:1336399

I am writing a generic method to get some data from a service and populate in the dynamic property name passed in the function. the value does gets assigned to the text box using angular.element assignment but does not gets populated in the model. following is 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 my controller method which internally uses a service which sends back a promise

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

attrModel is a property name in the scope object contentEntity but the name of the property is known ONLY dynamically via the method parameter.

I am writing a generic method to get some data from a service and populate in the dynamic property name passed in the function. the value does gets assigned to the text box using angular.element assignment but does not gets populated in the model. following is 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 my controller method which internally uses a service which sends back a promise

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

attrModel is a property name in the scope object contentEntity but the name of the property is known ONLY dynamically via the method parameter.

Share Improve this question edited Sep 8, 2014 at 13:21 Vikram asked Sep 8, 2014 at 13:10 VikramVikram 6,8779 gold badges52 silver badges61 bronze badges 18
  • 1 ng_model - is it typo? must be ng-model – Vladimir Gordienko Commented Sep 8, 2014 at 13:14
  • no need to set the value using val() when it is bound using ng-model ( with proper syntax) – charlietfl Commented Sep 8, 2014 at 13:15
  • You are selecting an element by id 'contentEntity.imgRollover' which doesn't exist – axelduch Commented Sep 8, 2014 at 13:16
  • 1 so add two params... pickImage('contentEntity', 'imgRollover') – Vladimir Gordienko Commented Sep 8, 2014 at 13:32
  • 1 @Vikram I proposed something else if you ever need to use an unknow n object depth – axelduch Commented Sep 8, 2014 at 14:48
 |  Show 13 more ments

3 Answers 3

Reset to default 3
<button class="btn" type="button" ng-click="pickImage('contentEntity', 'imgRollover')"></button>

$scope.pickImage = function (attrModel1, attrModel2) {
        ImageSelector.selectImage().then(function (value) {
                $scope.[attrModel1][attrModel2] = value;
        });
};

should work

I know this has already been well answered but I wanted to make a dynamic property creator. It splits attrModel by '.' and then edits $scope and adds and/or returns each property if it either exists already or not, we preserve the last key outside of the while loop so that the value just has to be appended to it.

$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;
        });
};

Of course, if you want to do it the angular way you'd have to use a service in order to do that, it could look like this

jsfiddle 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]];
            }
        };
    })

There is already an answer but, just like to post something for dynamic properties...

<!DOCTYPE html>
<html>

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

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

        value++;

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

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

      }

    </script>
  </head>

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

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

      <br/>
      <button ng-click="pickImage(test.obj)">test</button>
      <br/>
      display the value afoter button click,
      note there is no single quote
      <br/>
      value: {{ getValue(test.obj) }}


  </body>

</html>

本文标签: javascriptSet a property of scope object dynamically in Angular JsStack Overflow