我还不能在我的应用程序中使用“单页”应用程序概念,因为我们有遗留代码来缓慢但稳定地处理和“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());
}
};
}]);
关于javascript - AngularJS:从 <script type ="application/json"> 获取 json 数据到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28288231/