Jason
Jason

Reputation: 15931

nest ng-view inside a form

given the controller

function ctl($scope, $http) {
  $scope.postForm = function() {
    console.log("submitting form")
  }
}

and the view

  <form name="pform" ng-show="!error.Show">
    <div ng-view></div>
    <button type='button' value='Save' ng-click="postForm()" />
  </form>

The controller method postForm doesn't get called, however, if i move the form tag into the view the method is called. Is there a reason that this doesn't work as I expect it to? Is there another way to accomplish the goal of sharing the form controls across different views?

Update

my module and routeProvider are configured like this:

angular.module("profilemodule", [])
.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when("/info", { templateUrl: '/partials/profile/info.html', controller: ProfileController })
        .when("/user", { templateUrl: '/partials/profile/user.html', controller: ProfileController })
        .when("/introduction", { templateUrl: '/partials/profile/editor.html', controller: ProfileController })
        .otherwise({ redirectTo: '/info' });
}]).run(function ($rootScope, $location) {
    $rootScope.location = $location;
})

and the page includes some nav elements which are set based on the location service like so:

<div class="row">
    <div class="offset2 span10">
        <ul class="nav nav-pills">
            <li ng-class="{active: location.$$path.substring(0, '/info'.length) == '/info'}"><a href="#/info" >Information</a></li>
            <li ng-class="{active: location.$$path.substring(0, '/user'.length) == '/user'}"><a href="#/user" >User</a></li>
            <li ng-class="{active: location.$$path.substring(0, '/intro'.length) == '/intro'}"><a href="#/intro" >Introduction</a></li>
        </ul>
    </div>
</div>

<form name="pform" method="POST" ng-show="!error.Show">
   <div ng-view></div>
   <button type='button' value='Save' ng-click="postForm()" />
</form>

the ng-class statements works perfectly, is it because I've set the location property of $scope in the module's run method?

thanks,

jason

Upvotes: 4

Views: 2465

Answers (1)

Umur Kontacı
Umur Kontacı

Reputation: 35478

ng-view with routing creates a new scope with the controller, and you can't reach a child scope. Your submit action lies in the parent scope and the form data lies in the child scope (created by ng-view).

If you want to use common form controls, you can use ng-include, this directive gets template it and renders that in the current scope.

Move your form controls to a new template, then include them in all of your forms.

API reference:
http://docs.angularjs.org/api/ng.directive:ngInclude

Upvotes: 1

Related Questions