Answer the question
In order to leave comments, you need to log in
Why is it impossible to get the value of the input in the controller?
Please tell me why the input value is not passed to the controller. I seem to be doing everything right. I rechecked everything 10 times, re-read the documentation. In the test example, everything is ok, but nothing works in the worker.
The project itself is loaded here, you need to click on the "Other" item, the input text will open. After entering the value there and pressing the "test" button, "undefined" is written in the browser console. What could be the reason?
<div ng-show=" {{answer.id }} === 6 && showTextBox_1"> <!-- div for text-box -->
<div >
<input type="text" style="width:50%;" class="form-control" placeholder="Введите текст" ng-model="textboxValue_1"/>
</div>
<button ng-click="go()">
test
</button>
</div>
$scope.textboxValue_1;
$scope.go = function() {
console.log($scope.textboxValue_1);
}
Answer the question
In order to leave comments, you need to log in
Directives that remove the DOM (ng-if, ng-include, ng-repeat, etc.) create a child Scope with a prototype for your data. Therefore, if you write to the root of the child scope, for example, scope.textboxValue_1 = "...", then this variable will not be available from your scope, because the value changed in the child, not yours. Which is what happens in your case.
Therefore, it is recommended to use controllerAs, or store data in the "myModel.textboxValue_1" object, because myModel will refer to the same object from your scope and child scope.
The latest Angular Light and Angular 2 don't have this problem.
$scope.myModel = {
textboxValue_1:null
};
Read:
https://github.com/angular/angular.js/wiki/Underst...
tl/dr
This is related to the implementation of scope inheritance in angularjs. Inheritance is organized through object prototypes, and in this case only references are inherited. In your case, ng-model writes the result to its scope and we cannot read it from the parent scope.
As a rule, directives create their own scopes (but not always), including ng-model. Therefore, this point should be taken into account.
The simplest solution that won't look like a hack is the controllerAs syntax which was introduced in angular 1.2. So your controller will look like this:
function MyController() {
var vm = this;
this.textBoxValue = 'test';
}
<div ng-controller="MyController as myCtrl">
<input type="text" ng-model="myCtrl.textBoxValue" />
</div>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question