2015-05-27 21 views
1

有沒有辦法從AngularJS的html端訪問$ route?

我真的很想在HTML中做這樣的事情,並消除另一個$ scope函數。 (是的,我知道它不是真正的一些作品):

<button ng-disabled="!route.current.scope.currentform.$valid">

我在一個大角度的應用程序的工作,有點「在路上」的開發週期。目前我們已經決定實施表單驗證(不要問清單爲什麼不是1或2)。

我目前在頁腳「previous」和「next」中使用了兩個按鈕,這兩個按鈕都需要ng-disabled設置爲!$ scope.formname。$ valid。這需要在多個控制器/頁面上工作,因爲按鈕位於index.html的頁腳中。

我現在使用的代碼看起來是這樣的:

// Want to eliminate this isFormValid() method 
 
$scope.isFormValid = function() { 
 
    if ($route.current) { 
 
    if ($route.current.scope) { 
 
     return !$route.current.scope.currentform.$valid; 
 
    } 
 
    } 
 
}; 
 

 
$scope.prevPage = function() { 
 
    if (angular.isFunction($route.current.scope.PrevAction)) { 
 
    // do stuff particular to the current controller 
 
    $route.current.scope.PrevAction() 
 
    } 
 
}; 
 

 
$scope.nextPage = function() { 
 
    if (angular.isFunction($route.current.scope.NextAction)) { 
 
    // do stuff particular to the current controller 
 
    $route.current.scope.NextAction() 
 
    } 
 
};

和相應的按鈕代碼如下:

<div class="footer"> 
 
    <button id="main-prev-button" type="button" class="btn btn-primary previous" ng-click="prevPage($event)" ng-disabled="isFormValid()">Previous</button> 
 
    <button id="main-next-button" type="button" class="btn btn-primary next" ng-click="nextPage($event)" ng-disabled="isFormValid()">Next</button> 
 
</div>

每個頁面的代碼看起來是這樣的

<ng-form id="currentform" name="currentform"> 

    <label>Full Name</label> 
    <input type="text" class="form-control" ng-model="nl.firstName" id="firstName" placeholder="First Name" name="firstName" ng-minlength="5" ng-maxlength="20" ng-required="true"> 
    <pre>currentform.firstName.$error = {{ currentform.firstName.$error | json }}</pre> 

    <ng-messages for="currentform.firstName.$error"> 
    <ng-message when="required">You did not enter a field</ng-message> 
    <ng-message when="minlength">Your field is too short</ng-message> 
    <ng-message when="maxlength">Your field is too long</ng-message> 
    </ng-messages> 

</ng-form> 

回答

2

添加$route到根範圍$rootScope,然後使用$rootScope.$route訪問它在你的HTML /視圖。

E.g:

angular.module('myApp').run(['$rootScope', '$route', 
    function ($rootScope, $route) { 
     $rootScope.$route = $route; 
}]); 
+0

這工作得很好。我們一直試圖將運行區域作爲我們網站不同部分範圍繼承的良好起點。 – CarComp

相關問題