Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Get json data from <script type="application/json"> into controller

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


1 Answers

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

like image 70
Jonathan Palumbo Avatar answered Apr 09 '26 15:04

Jonathan Palumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!