Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I can't use the "single page" app concept yet with my application because we have legacy code to deal with and "angularize" our app slowly but steady. I need to add some Angular functionality to different forms that are still going to submitted via POST but not triggered by Ajax. So my idea to get the changed data after a POST to the server is this:

<script type="application/json" json-data ng-model="data">
    <?php echo json_encode($myData, true); ?>
</script>

What fails now for me is to get the json data from inside the script tag into my controllers scope. I've written a custom directive for that:

angular.module('app').directive('jsonData', [function() {
    return {
        restrict: 'A',
        scope: {
            ngModel: '='
        },
        link: function(scope, element, attributes, controller) {
            var object = JSON.parse(element.html());
            attributes.ngModel = object;
        },
        controller: function($scope) {
            console.log($scope.ngModel);
        }
    };
}]);

However, this doesn't update my $scope inside my angular controller (no, I don't mean the controller of the directive).

You can run this plunker to get an idea of my issue: http://plnkr.co/edit/O4FZUgN21LRRfqyDQCVT

share|improve this question
1  
Is this the behavior you are looking for? plnkr.co/edit/dLO0yHbY9soimHMnRDiy?p=preview –  Jonathan Palumbo Feb 2 at 23:16
    
Thank you, this seems to work, so my only issue was this scope[attributes.ngModel] = object ; line? Post it as answer and I'll flag it as correct. –  user3437727 Feb 3 at 10:01

1 Answer 1

up vote 1 down vote accepted

You should remove the isolate scope. Then you can populate a new scope variable using the ng-model attribute.

<script type="application/json" json-data ng-model="data">{"sample": "data"}</script>
<script type="application/json" json-data ng-model="data2">{"sample": "more data"}</script>
<script type="application/json" json-data ng-model="data3">{"sample": "even more data"}</script>
<pre>{{data | json}}</pre>
<pre>{{data2 | json}}</pre>
<pre>{{data3 | json}}</pre>
<pre>{{test | json}}</pre>

Directive

app.directive('jsonData', [function() {
    return {
        restrict: 'A',
        link: function(scope, element, attributes, controller) {
            scope[attributes.ngModel] = JSON.parse(element.html());
        }
    };
}]);

http://plnkr.co/edit/INyT5KTKaq5Hr6teOFiz?p=preview

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.