Ian Warburton
Ian Warburton

Reputation: 15726

Form elements not appearing in $scope

Here's the start of my form...

<div ng-form name="CustomerForm" ng-controller="Customer">

Here's my controller...

app.controller('Customer', ['$scope', function ($scope) {

   alert($scope.CustomerForm);
}]);

$scope.CustomerForm is undefined. Shouldn't the form be added to scope?

Upvotes: 9

Views: 7002

Answers (1)

Eric Hotinger
Eric Hotinger

Reputation: 9316

At the time of your alert statement, CustomerForm isn't within $scope yet.

Controllers are meant to:

  1. Create an initial state of a scope object.
  2. Add behavior to that scope object.

Read more here about controllers.


The "Solution?"

See here: DEMO

JS:

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

app.controller('Customer', ['$scope', function ($scope) {
    
    $scope.getFormName = function(){
        console.log($scope.CustomerForm.$name);
    }
}]);

HTML:

<div ng-form name="CustomerForm" ng-controller="Customer">
    <button ng-click="getFormName()">CLICK</button>
</div>

Upvotes: 13

Related Questions