Nikita
Nikita

Reputation: 2943

How to create a simple textarea without ng-Model in angular.js?

In my angular.js app, I have a textarea like this:

<textarea ng-model='model.content'>{{model.content}}</textarea>.

The user edits the content in the textarea and then clicks a button, at which point I record the current (previous) value of model.content, and then update it with the current text of textarea.

However, textarea immediately updates model.content as soon as its onchange event fires (because it's a 2-way binding), and by the time the button is clicked, model.content already contains the text of textarea, and I have no record of the previous value of model.content.

Question – how do I stop angular from updating the model? I don't want the model updated until the button is clicked. As you see I don't need a two-way binding at all. However, ng-model is required for the textarea directive. I've tried creating a custom directive but angular still treats any textarea tag as a directive requiring a two-way binding instead of an unknown html tag.

Upvotes: 2

Views: 1518

Answers (3)

Maxim Shoustin
Maxim Shoustin

Reputation: 77910

You can use angular.copy() utility that clones (makes copy) of the model and creates new instance.

See Docs HERE

HTML

<div ng-controller="fessCntrl">
    <div class="text-area-container">
        <textarea   rows="2" ng-model="textModel"></textarea>
    </div>

    <button ng-click="commit(textModel);">Commit</button>

    <pre>copy: {{copy|json}}</pre>
</div>

JS

var fessmodule = angular.module('myModule', []);

fessmodule.controller('fessCntrl', function ($scope) {

    $scope.copy = '';

    $scope.commit = function (textModel) {
        $scope.copy = angular.copy(textModel);
    };
});
fessmodule.$inject = ['$scope'];

Demo Fiddle

Upvotes: 1

musically_ut
musically_ut

Reputation: 34288

You can create a two way binding yourself.

You will keep a local variable localContent which will hold the content of the textarea. Then set up a callback on the button which will set model.content = localContent. Further, set up a $watch on the actual model.content and update localContent when the original model changes.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691983

You're doing it backward. Instead of trying to save the original content when the user has finished editing the value (and the original content is thus already modified), you should save it before he does it, when the model is populated and the page displayed.

Also, you don't need {{model.content}}inside the textarea.

Upvotes: 0

Related Questions