0

I need to set the data-ng-model attribute of an html input field via javascript. I know I can't do

element.data-ng-model = "...";

because of the dashes. So I tried

element.["data-ng-model"] = "...";

and

element.dataNgModel = "...";

and

element.datangmodel = "...";

None of these seem to work properly. Any suggestions?

2 Answers 2

2

Try:

element.setAttribute("ng-model", "...");

or if you have JQuery:

$(element).attr("ng-model", "...");
Sign up to request clarification or add additional context in comments.

Comments

0

If you need to set the model with javascript you can set it in the controller see below From the angular docs https://docs.angularjs.org/api/ng/directive/ngModel

(function(angular) {
  'use strict';
  angular.module('getterSetterExample', [])
    .controller('ExampleController', ['$scope',
      function($scope) {
        var _name = 'Brian';
        $scope.user = {
          name: function(newName) {
            // Note that newName can be undefined for two reasons:
            // 1. Because it is called as a getter and thus called with no arguments
            // 2. Because the property should actually be set to undefined. This happens e.g. if the
            //    input is invalid
            return arguments.length ? (_name = newName) : _name;
          }
        };
      }
    ]);
})(window.angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-app="getterSetterExample">
  <div ng-controller="ExampleController">
    <form name="userForm">
      <label>Name:
        <input type="text" name="userName" ng-model="user.name" ng-model-options="{ getterSetter: true }" />
      </label>
    </form>
    <pre>user.name = <span ng-bind="user.name()"></span></pre>
  </div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.