0

I have very basic functionality which is like get text value on click function. I have a text box inside ng-if. But when I am trying to get the value it says 'undeifned' I red about it and came to know that ng-if create its own scope. So if it is true then why click function is working which is defined in controller. Both are defined in controller. plnkr

app.controller('MainCtrl', function($scope) {
  $scope.comment="";
  $scope.showBox = function (){
    $scope.showTextBox = true;
  }
  $scope.getComment = function (){
    alert($scope.comment);
    $scope.showTextBox = false;
  }

});
Jitender
  • 7,593
  • 30
  • 104
  • 210
  • Your `ng-model` should always have a dot in it: http://stackoverflow.com/a/17607794/373655 . You may want to look into using the "controller as" syntax as it will take care of this for you – rob Nov 26 '15 at 19:00
  • You can use ng-show="CONDITION" instead of ng-if. It will work. – Hari Das Jun 03 '16 at 06:36

2 Answers2

0

ng-if creates a new child scope. ng-show does not. I'm guessing the $scope.comment is defined inside the ng-if.

If you don't want to use ng-show, sometime using an object instead of a simple variable will work. Ex:

$scope.comment= { c: "" };
alert($scope.comment.c);
<textarea ng-model="comment.c">

Updated plunkr: http://plnkr.co/edit/DewF13GWVIS8bHQIIAbC?p=preview

Mike
  • 335
  • 4
  • 20
0

Always try to use dot(.) in your scopes to save yourself from inheritance issues in AngularJS.

Try to add an object and add properties over it, like - $scope.data = {}; and then add $scope.data.comment = {};

Code -

app.controller('MainCtrl', function($scope) {
  $scope.data = {};
  $scope.data.comment="";
  $scope.showBox = function (){
    $scope.data.showTextBox = true;
  }
  $scope.getComment = function (){
    alert($scope.data.comment);
    $scope.data.showTextBox = false;
  }

});

http://plnkr.co/edit/33ENoFi6qHRPDJUjc6tc?p=preview

swapnesh
  • 26,318
  • 22
  • 94
  • 126