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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With