BhajjiMaga
BhajjiMaga

Reputation: 97

Directive should execute only once

I have a directive to show the content of JSON file after formatting.

.directive('jsonText', function() {
return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
        ngModel: "="
    },
    link: function(scope, element, attr, ngModel) {
        update();
        function update() {
            var data = scope.ngModel;
            console.log(JSON.stringify(attr)+" to ---> "+angular.toJson(data,true));
            scope.ngModel = angular.toJson(data,true);
        }

    }
};});

My html code is

<div class="col-md-12">
    <textarea ng-model="jsondata" readonly json-text rows="10" name="jsonfile" id="jsonfile" style="resize: none"></textarea>
</div>

So what happens it is multi step form so i navigate to this code multiple times.

So first time when it reaches this it is properly formatted.

{
   "subjectareaname": "Defects",
   "feedname": "Feed for Jira",
   "description": "Feed for Jira",
   "datafeedfor": "application",
   "name": "Log4jphp"
}

But the second time it happens something like this.

"{\n  \"subjectareaname\": \"Defects\",\n  \"feedname\": \"Feed for Jira\",\n  \"description\": \"Feed for Jira\",\n  \"datafeedfor\": \"application\",\n  \"name\": \"Log4jphp\"\n}"

How do i avoid this? Is there any way that i can force it work only once.

Upvotes: 1

Views: 937

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

It's because you're overwriting your scope.ngModel with this line:

 scope.ngModel = angular.toJson(data,true);

That means next time it comes in, the data will actually be changed. Angular already comes with a nice json filter for you so to accomplish what you're doing you can just have something like this:

 <pre>{{ jsonData | json }}</pre>

You can see it in action in this fiddle: http://jsfiddle.net/o0d5kdv6/

Upvotes: 2

Related Questions