在 AngularJS 中从 html 端访问 $route 的简单方法

Easy way to access $route from html side in AngularJS

有没有办法从 AngularJS 的 html 端访问 $route?

我真的很想在 HTML 中做这样的事情并消除另一个 $scope 函数。 (是的,我知道它不是真正有效的东西):

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

我正在开发一个大型 angular 应用程序,它在开发周期中有点 'down the road'。这个时候我们已经决定实现表单验证(不要问为什么它不是列表中的 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>

$route 添加到根范围 $rootScope,然后使用 $rootScope.$route.

在您的 html/view 中访问它

例如:

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