如何使用angularjs将JSON数据从FirstCtrl发送到secondCtrl。
谁能帮我解决这个问题...
First.js:
angular.module('myApp')
.controller('FirstCtrl', function ($scope) {
//firstCtrl json data
$.getJSON("sample.json", function (json) {
console.log(json);
});
});
Second.js:
angular.module('myApp')
.controller('secondCtrl', function ($scope) {
//get the firstCtrl json data here
});
我还建议使用一种从控制器获取数据并向控制器返回数据的服务。
我们创建两个控制器,然后创建具有两个功能的服务:1.一个用于获取json数据2.一个用于返回json数据
像这样:
'use strict';
angular.module('myApp', [])
.controller('FirstCtrl', function( $scope, myService ){
//we create or get the json object
$scope.myjsonObj = {
'animal':'cat',
'feed':'frieskies',
'color':'white',
'sex':'male'
};
//pass the json object to the service
myService.setJson($scope.myjsonObj);
})
.controller('SecondCtrl', function( $scope, myService ){
//call service getJson() function to get the data
$scope.myreturnedData = myService.getJson();
})
.factory('myService', function(){
var myjsonObj = null;//the object to hold our data
return {
getJson:function(){
return myjsonObj;
},
setJson:function(value){
myjsonObj = value;
}
}
});
HTML部分将是:
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
{{myjsonObj}}
</div>
<hr>
<div ng-controller="SecondCtrl">
{{myreturnedData.animal}}
{{myreturnedData.feed}}
{{myreturnedData.color}}
{{myreturnedData.sex}}
</div>
希望有帮助,祝你好运。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句