简体   繁体   English

AngularJS:从中获取json数据<script type=“application/json”> into controller

[英]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. 我需要将一些Angular功能添加到仍然通过POST提交但不是由Ajax触发的不同表单中。 So my idea to get the changed data after a POST to the server is this: 所以我想在POST到服务器后获取更改的数据是这样的:

<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. 对我来说现在失败的是将脚本标记内的json数据放入我的控制器范围。 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). 但是,这不会更新我的角度控制器内的$scope (不,我不是指指令的控制器)。

You can run this plunker to get an idea of my issue: http://plnkr.co/edit/O4FZUgN21LRRfqyDQCVT 你可以运行这个plunker来了解我的问题: http ://plnkr.co/edit/O4FZUgN21LRRfqyDQCVT

You should remove the isolate scope. 您应该删除隔离范围。 Then you can populate a new scope variable using the ng-model attribute. 然后,您可以使用ng-model属性填充新的范围变量。

<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 http://plnkr.co/edit/INyT5KTKaq5Hr6teOFiz?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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