Angular - set ng model using scope variable

Isn't it necessary to do this? Since I can not get it to work.

In my controller I have

$scope.test = "someValue" 

and in my opinion

 <input ng-model="test" /> 

What I expect to see

 <input ng-model="someValue" /> 

However, the ng model remains installed as "test".

How to resolve this?

+5
source share
2 answers

This is not an ng-model method. If you have a scope variable, as in your case test , and the value of this variable will be reflected in the value property of your input . This means that someValue will be displayed in input . In other words: ng-model is a directive that communicates with, for example, input, selection, textarea (or user-defined form control) in a property in an area using NgModelController .

NgModelController provides an API for the ngModel directive. the controller contains services for data binding, validation, CSS updates, and formatting and parsing of values

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 above example also shows some best practices that mean using the controllerAs syntax for your view and clearly declaring your controller signature.

+2
source

Show your controller code. However, I have demonstrated below that it should work.

 angular.module('myApp', []); angular.module('myApp').controller('myCtrl', function($scope) { $scope.test = "somevalue"; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="myApp"> <form ng-controller="myCtrl"> <input type="text" ng-model="test" /> </form> </body> 

ng-model simply represents a binding object. This will not change. What changes does the value value , which corresponds to the value that the ng-model object takes.

0
source

Source: https://habr.com/ru/post/1234810/


All Articles