【问题标题】:Can't access form inside AngularJS controller无法访问 AngularJS 控制器中的表单
【发布时间】:2014-12-18 04:55:21
【问题描述】:

无法从我的控制器访问表单变量,当我尝试通过 $scope.locationForm 访问它时,我得到了“未定义”,但是当我调用 console.log($scope) 时,我可以在控制台中看到位置表单。

我的 HTML 代码

<div ng-controller="LocationsController as ctrl">   
<form class="form-inline" name="locationForm">
    <div class="form-group">
        <!-- <div class="input-group"> -->
            <label for="location-name">Название населенного пункта</label>
            <input required
                   name="name"
                   ng-model="ctrl.location.name" type="text" class="form-control" id="location-name" placeholder="Название населенного пункта">
            <label for="location-name">Район</label>
            <select required
                    name="region_id" 
                    ng-model="ctrl.location.region_id" 
                    ng-options="region.id as region.name for region in ctrl.regions" class="form-control" placeholder="Название района"></select>
            <input ng-click="ctrl.save()"
                   ng-disabled="locationForm.$invalid" type="submit" class="btn btn-default" value="Cохранить">
            <a class="btn btn-default" ng-click="ctrl.reset()" ng-show="locationForm.$dirty">Сброс</a>
        <!-- </div> -->
    </div>
</form>

我的控制器代码:

function LocationsController($scope, Location, Region, $q) {
var lc = this,
    l_index;
  lc.form ={};
  lc.regions = lc.locations = [];
  lc.regions = Region.query();
  lc.regions.$promise.then(function(data) {
      lc.locations = Location.query();
  });
  lc.getRegion = function (id) {
    return lc.regions.filter(function(obj) {
        return obj.id == id;
    })[0].name;
  };
  console.log($scope);
  // console.log($scope.locationForm);
  lc.reset = function () {
      lc.location = new Location;
  }
  lc.reset();

};

【问题讨论】:

  • 我认为问题是 LocationControllerform 元素被编译之前被初始化 - jsfiddle.net/arunpjohny/jcvqdf06/1
  • 你知道怎么解决吗?
  • 你想达到什么目的
  • 我需要locationForm$setPristine 方法才能在重置功能中使用它
  • 在超时时调用重置 - $timeout(function(){lc.reset();})

标签: javascript angularjs


【解决方案1】:

问题是当LocationsController 被初始化时,form 元素还没有被编译。因此,一种可能的技巧是使用像

这样的超时
function LocationsController($scope, Location, Region, $q, $timeout) {
    //then later
    $timeout(function(){lc.reset();})
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多