Sophie McCarrell
Sophie McCarrell

Reputation: 2871

How do I attach a change event to a textarea that already has a one way binding that is filtered?

I have a text area that is already bound with a filter, so it'll load with the correct info on page load, but now I want to change a model when the text area is changed, but once I add a model and change event the initial binding stops working.

Here is the HTML as a one way binding, which works:

<textarea>{{mainboard | textboard}}</textarea>

My thinking was that I would add a change event, which errors without a model, so I added a model, like so:

<textarea ng-model="textmainboard" ng-change="updateMainboard()">{{mainboard | textboard}}</textarea>

How can I have a two way binding, with the one way being filtered (the filter in this example is the textboard service)?

EDIT: Here is a js fiddle of me trying to do the blur, which shouldn't require a model: http://jsfiddle.net/vjkgH/

EDIT: The exact use case is I have a list of items. The list of items is displayed as li elements and displayed in a textarea with duplicates shown as "3x itemb". The list of items can be changed in two way, by hitting an add button or by changing the textarea.

Here is an example state:

<ul>
 <li>item1</li>
 <li>item1</li>
 <li>item2</li>
</ul>
<textarea>
 2x item1
 1x item2
</textarea>

Upvotes: 3

Views: 3076

Answers (1)

Sophie McCarrell
Sophie McCarrell

Reputation: 2871

For my own use case, the issue was that angular only runs $watch [in other words, updates your DOM] when your new variable, doesn't equal your old variable, unless the third parameter of the $watch function is set to true.

for an ng-model on a text area or any text thing, the third parameter is always false, so it compares the old array to the new array, which are equal to the same reference, and therefor, angular doesn't think the array changed.

I've requested a feature on github from the angular community that an option is somehow added to allow objectEquality to be set to true when doing ng-model. Otherwise you would need to write your own directive that mimics ng-model, but also sets the $watch's third parameter to true.

So, to get my desired result, I used the answer to this SO QA: How to do two-way filtering in angular.js? and have all my updates to the array, clone the array, so there is always a new reference. The inefficiency worries me, but my old laptop appears to handle it lightning fast, so good enough.

Upvotes: 1

Related Questions