2013-01-09 20 views
4

給出的控制器巢NG-視圖

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

和視圖

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

控制器方法postForm不會被稱爲然而,如果我的形式標記移動到查看調用的方法。有沒有這樣的理由,這不符合我的預期?是否有另一種方式來實現跨不同視圖共享表單控件的目標?

更新

我模塊和routeProvider配置是這樣的:

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; 
}) 

和頁面包括基於位置的服務集,像這樣一些導航元素:

<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> 

ng-class聲明完美,是因爲我設置了location模塊的run方法中$scope的屬性?

感謝,

傑森

+1

是您在ngView的$ routeProvider定義控制器(CTL)?如果是這樣,它超出了它的範圍。嘗試在窗體標籤上添加一個新的控制器(例如ng-controller =「formCtrl」),並在那裏定義postForm函數。 – asgoth

+0

它是,請看看我更新的問題,因爲我在包含該表單的同一頁面上使用該控制器中的其他屬性並且它正在工作。 – Jason

+1

ng-class的作用是因爲你已經在$ rootScope上設置了位置 - 每個子作用域都從根繼承,因此可以訪問它的屬性。 – matys84pl

回答

1

ng-view與路由建立與控制器一個新的範圍,你不能達到一個孩子的範圍。您的提交操作位於父範圍內,表單數據位於子範圍內(由ng-view創建)。

如果您想使用常見的窗體控件,您可以使用ng-include,該指令獲取模板並呈現當前範圍

將您的表單控件移動到一個新模板,然後將它們包含在所有表單中。

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