garethb garethb - 19 days ago 5
AngularJS Question

ngModel undefined when using directive - Angularjs controller

My ngModel is undefined when using the ngPattern directive. If I remove ngPattern, the ngModel works as expected. See plnkr.

Note how vm.condition does not show when typing a value in the text box, but as soon as the ngPattern is removed, vm.condition shows as expected.

HTML

<body ng-controller="MainCtrl as vm">
<div ng-form="vm.frmTest">
<input id="txtHealth" name="txtHealth" type="text" ng-model="vm.condition" ng-pattern="/^(.+)$/g">
<div class="help-block" ng-messages="vm.frmTest.txtHealth.$error" ng-show="vm.frmTest.txtHealth.$invalid">
<p ng-message="pattern">Error.</p>
</div>
</div>
<span>{{vm.condition}}</span>
</body>


JS

app.controller('MainCtrl', function($scope) {
this.condition = '';
});


NOTE: This is a dumbed down version showing the issue. My directive is showing the same issue.

Answer

It is probably because of the pattern string that you are using in your directive. Try having a $scope bind and check your directive. You can check the relative PLUNKER example here:

Demo Example

HTML:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-messages.js"></script>
        <script src="script.js"></script>
  </head>

  <body ng-controller="MainCtrl as vm">
    <div ng-form="vm.frmTest">
      <input id="txtHealth" name="txtHealth" type="text" ng-model="vm.condition" ng-pattern="re">
      <div class="help-block" ng-messages="vm.frmTest.txtHealth.$error" ng-show="vm.frmTest.txtHealth.$invalid">
        <p ng-message="pattern">Error.</p>
      </div>
    </div>
    <span>{{vm.condition}}</span>
  </body>

</html>  

JS:

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

app.controller('MainCtrl', function($scope) {
  this.condition = '';
  $scope.re = /^(.+)$/g;
});