1

Can't access form variable from my controller, when i try to access it by $scope.locationForm i've got 'undefined', but when i call console.log($scope) i can see in console there have loactionForm.

My HTML code

<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>

My Controller code:

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();

};

6
  • I think the problem is the LocationController is initialized before the form element is compiled - jsfiddle.net/arunpjohny/jcvqdf06/1 Commented Dec 18, 2014 at 5:10
  • Do you know how to fix it? Commented Dec 18, 2014 at 5:14
  • what are you trying to achieve Commented Dec 18, 2014 at 5:33
  • i need a $setPristine method of locationForm to use it in the reset function Commented Dec 18, 2014 at 5:38
  • call the reset in a timeout - $timeout(function(){lc.reset();}) Commented Dec 18, 2014 at 5:44

1 Answer 1

1

The problem is when the LocationsController is initialized the form element is not yet compiled. So one possible hack is to use a timeout like

function LocationsController($scope, Location, Region, $q, $timeout) {
    //then later
    $timeout(function(){lc.reset();})
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.