Angular JS access form in scope inside Angular Boo

2019-07-26 06:36发布

问题:

I have a form in an Angular JS 1.4.1 prototype. I have a class on it set when it's dirty. I am trying to simulate someone "saving" the form, and therefore it's not dirty, it's "saved" so the changes are still present, but no longer dirty.

Form fragment:

<div class="override">
  <tabset>
    <tab heading="My Tab">
      <form name="overridesForm">
        <p><input ng-model="rd.isOverriden" type="checkbox"> Foobar</p>
        <div class="buttons save-cancel">
          <button class="btn btn-default btn-xs" ng-click="overridesForm.reset();overridesForm.$setPristine()">Cancel</button>
          <button class="btn btn-primary btn-xs" ng-click="overridesForm.$setPristine()">Save with Inline</button>
          <button class="btn btn-primary btn-xs" ng-click="saveData()">Save with Inline</button>
        </div>
      </form>
    </tab>
    <tab heading="Some other Tab">
      blah
    </tab>
  </tabset>
</div>

Setting the form to pristine only works for me inline, not in a function in the controller. So this works:

<button ng-click="overridesForm.$setPristine()">Save</button>

But not this:

<button ng-click="saveData()">Save</button>

//controller:
$scope.saveData = function () {
    $scope.overridesForm.$setPristine();
    toastr.success('Success', 'Data was saved.');
  };

I get a runtime error "no object overridesForm defined".

For reasons I have yet to figure out, it works in this codepen but not my project.

UPDATE:

After searching about accessing a form in trancluded content, I hit upon this:

 <button ng-click="saveData(overridesForm)">Save with Inline</button>

and assign this in controller:

  $scope.saveData = function(form) {
    $scope.overridesForm = form;
    $scope.overridesForm.$setPristine();
  };

Not sure if this is best practice, but it works. Updated the codepen.