指令只应执行一次

时间:2015-10-07 12:26:10

标签: angularjs

我有一个指令,用于在格式化后显示JSON文件的内容。

.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);
        }

    }
};});

我的HTML代码是

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

所以它会发生多步形式,所以我多次导航到这个代码。

所以第一次到达它时,它的格式正确。

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

但第二次发生这样的事情。

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

我该如何避免这种情况?有什么办法可以强迫它只运作一次。

1 个答案:

答案 0 :(得分:2)

这是因为你用这一行覆盖了scope.ngModel:

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

这意味着下次进入时,数据实际上会被更改。 Angular已经为你提供了一个漂亮的json滤镜,所以要完成你正在做的事情,你可以得到这样的东西:

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

你可以在这个小提琴中看到它:http://jsfiddle.net/o0d5kdv6/

相关问题