【问题标题】:Easy way to access $route from html side in AngularJS在 AngularJS 中从 html 端访问 $route 的简单方法
【发布时间】:2015-08-09 15:39:06
【问题描述】:

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

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

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

我正在开发一个大型 Angular 应用程序,该应用程序在开发周期中有点“走下坡路”。这时候我们决定实现表单验证(不要问为什么它不是列表中的 1 或 2)。

我目前在页脚“上一个”和“下一个”中使用两个按钮,这两个按钮都需要 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>

【问题讨论】:

    标签: javascript html angularjs routes


    【解决方案1】:

    $route 添加到根范围$rootScope,然后使用$rootScope.$route 在您的html/view 中访问它。

    例如:

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

    【讨论】:

    • 这很好用。我们一直在尝试使用运行区域作为我们网站不同部分的范围继承的良好起点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2018-02-09
    • 1970-01-01
    相关资源
    最近更新 更多