简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM