Angular - Set ng-model using scope variable

11,849

That's not the way ng-model works. If you have a scope variable, as in your case test and value of this variable will reflect in the value property of your input. This means that someValue will be visible in the input. In other words: ng-model is a directive that binds to, e.g. an input,select, textarea (or custom form control) to a property on the scope using the NgModelController.

NgModelController provides API for the ngModel directive. The controller contains services for data-binding, validation, CSS updates, and value formatting and parsing

Here is an example:

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

app.controller('TestController', TestController);

function TestController() {
  var vm = this;

  vm.myModel = "This is the model value";
  vm.selectedOption = undefined;

  vm.options = [{
    id: '1',
    name: 'Option A'
  }, {
    id: '2',
    name: 'Option B'
  }, {
    id: '3',
    name: 'Option C'
  }];
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

<body ng-app="myApp" ng-controller="TestController as vm">
  <input type="text" ng-model="vm.myModel" />

  <select name="mySelect" id="mySelect" ng-model="vm.selectedOption">
    <option ng-repeat="option in vm.options" value="{{option.id}}">{{ option.name }}</option>
  </select>
  
  <pre ng-if="vm.selectedOption">Selected Option: {{ vm.selectedOption }}</pre>
</body>

The example above also shows some best practices, means using controllerAs syntax for your view and a clear declaration of your controller signature.

Share:
11,849

Related videos on Youtube

user2085143
Author by

user2085143

Updated on June 04, 2022

Comments

  • user2085143
    user2085143 about 2 years

    Is this something one should not do? As I am unable to get it to work.

    In my controller I have

    $scope.test = "someValue"
    

    and in my view

    <input ng-model="test" />
    

    What I am expecting to occur

    <input ng-model="someValue" />
    

    However, ng-model stays as being set to "test".

    How do I resolve this?

    • Harshal Carpenter
      Harshal Carpenter over 8 years
      What is the attribute that you want to set ? or is it that text value be "someValue"?
  • user2085143
    user2085143 over 8 years
    Thank you, I am always on the lookout for tips for best practices. I can get this to work for a simple input in my view but not for the one I want. I think the issue I am having is I am trying to set the ng-model of a <select> which is using the chosen plugin, and which is also a tabbed view.
  • LordTribual
    LordTribual over 8 years
    Updated my example above for your needs. Now you can check the <select>.