表单验证不在angularjs中工作

时间:2014-08-14 17:15:23

标签: angularjs controller

-----IN APP CONFIG-----
$routeProvider.
        when("/", {redirectTo: "/dashboard"}).
        when("/dashboard", {template: "<div ng-include='include'>", controller="xCtrl" }).
        .otherwise({redirectTo: "/404"})

-----IN xCtrl-----
app.controller("xCtrl",function($rootScope,$scope,$filter) {
     $scope.include = "pages/abc.html";
     var original;
    $scope.filters = {p_key: ""},
    $scope.showInfoOnSubmit = !1, original = angular.copy($scope.filters),
    $scope.revert = function () {
         return $scope.filters = angular.copy(original),$scope.projectListFilters.$setPristine()
    }, $scope.canRevert = function () {
        return!angular.equals($scope.filters, original) || !$scope.projectListFilters.$pristine
    }, $scope.canSubmit = function () {
        return $scope.projectListFilters.$valid && !angular.equals($scope.filters, original)
    }, $scope.submitForm = function () {
        return $scope.showInfoOnSubmit = !0, $scope.revert()
    }
})

---- IN pages/abc.html ----

    <form name="projectListFilters" data-ng-submit="submitForm()" novalidate>
    <input type="text" data-ng-model="filters.p_key" />
     <button type="submit"
            class="btn btn-primary btn-sm"
            data-ng-disabled="!canSubmit()">Sumbit
    </button>
    <button id="reset" type="reset" class="btn btn-sm btn-warning"
            data-ng-disabled="!canRevert()"
            data-ng-click="revert()">Revert Changes
    </button>
    </form>

此代码中存在关于$ valid,$ pristine of undefined object的JavaScript错误。但是如果我们在pages/abc.html文件中指定控制器 例如:
         <form name="projectListFilters" data-ng-submit="submitForm()" novalidate data-ng-controller="xCtrl">
 工作良好。这里的错误是什么?

1 个答案:

答案 0 :(得分:1)

使用templateUrl,而不是template

{
    templateUrl: "pages/abc.html",
    controller: "xCtrl",
}

这将pages/abc.html使用xCtrl作为其控制器。你现在的方式是,只有带有include的<div>有控制器,但是包含的页面没有它。

来自ngInclude

  

该指令创建新范围。