ThePearl ThePearl - 5 months ago 45
AngularJS Question

cant access form inside an accordion

Here's my code sample:

<html ng-app="helloApp">
<head>
<title>HelloWorld</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script src="js/ui-bootstrap-tpls-0.12.1.js"></script>
<script src="js/example.js"></script>
</head>

<body>
<div class="page-header">
<h1>Hello World Sample Program</h1>
</div>
<div ng-controller="HelloCtrl">

<form class="form-horizontal" role="form" name="TestForm">
<div class="form-group">
<label class="col-md-2 control-label">Type Your Name</label>
<div class="col-md-4">
<input type="text" ng-model="name" class="form-control" value="{{name}}" required/>
<span>Hello {{ name }}!</span>
</div>
</div>
</form>

</div>

</body>




and JavaScript:

(function() {

var helloApp = angular.module("helloApp", ['ui.bootstrap']);

helloApp.controller("HelloCtrl", ['$scope',
function($scope) {
// $scope.name = "calvin hobbes";
$scope.$watch('TestForm.$valid', function() {
console.log("watching " + $scope.TestForm.$valid);
});
}]);
})();


This works just fine.

I can see that form is being watched on console and it changes from false to true as I type.

But, I need the form inside an accordion, like this:

<div ng-controller="HelloCtrl">
<accordion close-others="false" >
<accordion-group is-open="true" is-disabled="false">
<form class="form-horizontal" role="form" name="TestForm">
<div class="form-group">
<label class="col-md-2 control-label">Type Your Name</label>
<div class="col-md-4">
<input type="text" ng-model="name" class="form-control" value="{{name}}" required/>
<span>Hello {{ name }}!</span>
</div>
</div>
</form>
</accordion-group>
</accordion>
</div>


The form is not recognized anymore.

I get the following error. How do I solve it?

TypeError: Cannot read property '$valid' of undefined
at Object.fn (example.js:12)
at l.$digest (angular.min.js:124)
at l.$apply (angular.min.js:126)
at angular.min.js:17

Answer

accordion and accordion-group creates new scope.

TestForm's controller will be updated in these scope but not in controller's scope.

To access the TestForm in controller's scope make the below code changes.

Markup

<form class="form-horizontal" role="form" name="forms.TestForm">

Controller

  $scope.forms = {}
  $scope.$watch('forms.TestForm.$valid', function() {
        console.log("watching " + $scope.forms.TestForm.$valid); 
    });

Here is the working plnkr: http://plnkr.co/edit/IP6mMY6Jf0zzBoG9kMLx?p=preview

Comments