Thursday, 12 September 2013

AngularJS with $resource and custom formatter/parser directive not working

AngularJS with $resource and custom formatter/parser directive not working

Here's an example:
http://plnkr.co/edit/ezTUdoDKhCUGX3848VLp
HTML:
<p>Hello {{data | json}}!</p>
<div>
<textarea myconverter ng-model="data"></textarea>
</div>
JavaScript:
var app = angular.module('plunker', ['ngResource']);
app.controller('MainCtrl', function($scope, $resource) {
$scope.data = $resource('some-data.json').get({});
})
.directive('myconverter', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
function fromJson(json) {
var out = JSON.stringify(json, null, 2);
return out;
}
function toJson(text) {
return JSON.parse(text);
}
ngModel.$parsers.push(toJson);
ngModel.$formatters.push(fromJson);
}
};
})
;
The simple Hello part works fine, when the AJAX call returns, it is
updated with the correct data. But the textarea is never updated. If I set
a breakpoint, it appears that it is given an object with no data (but I
can see the $resource methods). If I change the textarea to point to a
field of the "data" object, it works as expected.

No comments:

Post a Comment