Phil Sandler
Phil Sandler

Reputation: 28046

AngularJS Passing Scope?

I'm actually not sure what the title of the question should be, as it's not clear to me what I am missing.

I have boiled this down to a very simple example (the actual case is more complex). I have a text box and button inside of an ng-switch. The switch, I've read, creates it's own local scope.

What I want to do pass the value of the text box to a function when the button is clicked. In the function, I will do what needs to be done with the value, then clear the text box. I'm struggling to find the right way to do this.

Controller Code:

$scope.temp = 1;

$scope.tempCall = function (tempModel) {
    tempModel = ""; //this doesn't work
    $scope.tempModel = ""; //nor does this
};

HTML/Template:

<div ng-switch on="temp">
    <div ng-switch-when="1">
        <input ng-model="tempModel" />
        <input type="button" ng-click="tempCall(tempModel)" />
    </div>
    <div ng-switch-when="2">TWO</div>
</div>

I believe I can actually traverse the scope from the parent or root scope and clear the value, but that doesn't "feel" correct. What is the correct (Angular) way to clear this value?

Upvotes: 2

Views: 6399

Answers (2)

Derek Ekins
Derek Ekins

Reputation: 11391

When you are working with primitive values in angular scopes, you cannot overwrite a value in a parent scope from a child scope. This is because angular uses javascript prototypal inheritance.

What you could do in this case is create an object in the parent scope, then you can update the values on that in the child scope. Because you are not overwriting the object (only properties attached to it) the references work.

I created a demo of this on plunk you can view it here

$scope.temp = 1;
$scope.tempModel = {};

$scope.tempCall = function () {
  $scope.tempModel.previous = $scope.tempModel.value
  $scope.tempModel.value = "";
};

<div ng-switch on="temp">
  <div ng-switch-when="1">
      <input ng-model="tempModel.value" />
      <input type="button" ng-click="tempCall()" />
      {{tempModel.previous}}
  </div>
  <div ng-switch-when="2">TWO</div>

Upvotes: 3

Dan
Dan

Reputation: 63119

Here's one way to do it:

<input type="button" ng-click="tempCall(tempModel);tempModel='';" />

Probably the more "Angular way" would be to use a dot in your model like:

<input type="text" ng-model="tempModel.value" />

Then call your function by passing the tempModel object like:

<input type="button" ng-click="tempCall(tempModel)" />

Then you will be able to clear the value with:

$scope.tempCall = function (tempModel) {
    tempModel.value = "";
};

Here is a fiddle

To prevent databinding issues, "the rule of thumb is, if you use ng-model there has to be a dot somewhere." Miško Hevery

Upvotes: 1

Related Questions