javascript - AngularJS:从 <script type ="application/json"> 获取 json 数据到 Controller

标签 javascript json angularjs

我还不能在我的应用程序中使用“单页”应用程序概念,因为我们有遗留代码来缓慢但稳定地处理和“Angular 化”我们的应用程序。我需要向仍将通过 POST 提交但不由 Ajax 触发的不同表单添加一些 Angular 功能。所以我想在 POST 到服务器后获取更改的数据是这样的:

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

现在对我来说失败的是从脚本标记内部获取 json 数据到我的 Controller 范围内。我为此编写了一个自定义指令:

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);
        }
    };
}]);

但是,这不会更新我的 Angular Controller 内的 $scope(不,我不是指指令的 Controller )。

您可以运行这个 plunker 来了解我的问题:http://plnkr.co/edit/O4FZUgN21LRRfqyDQCVT

最佳答案

您应该删除隔离范围。然后您可以使用 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>

指令

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

关于javascript - AngularJS:从 &lt;script type ="application/json"> 获取 json 数据到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28288231/

相关文章:

.net - 有没有办法使用 WCF Web API 控制 JSON 格式?

angularjs - Angular Material 中的可关闭标签

javascript - jQuery 表格滚动

javascript - php echo 单引号并结束 javascript 的脚本

javascript - 如何在不同的函数中使用变量?

javascript - 如何在 Angular JS Web 应用程序中使用 ckeditor?

angularjs - 在开发两个独立的应用程序(Angular 应用程序和 Laravel 应用程序)时保护 API 端点

javascript - 使用 PDFObject 显示加载指示器

javascript - 将多个 DataTable 序列化为 JSON

php - 添加到购物车按钮不起作用 - 拒绝获取不安全 header "X-JSON"