[英]AngularJS - How to pass data to a controller
I'm having a hard time passing data to a controller. 我很难将数据传递到控制器。 My scenario is that I have a function that gets a json object and I need to pass that object to a controller that does the rest of the work. 我的情况是,我有一个获取json对象的函数,我需要将该对象传递给执行其余工作的控制器。 Below is what I'm working with: 以下是我正在使用的工具:
Getting the data before DOM loads and save it in the Data
variable. 在DOM加载之前获取数据并将其保存在Data
变量中。
$.ajax({
url: "/_api/web/lists/getbytitle('Consultant%20Profile')/items?$filter=ID%20eq%20"+curItemId,
type: "GET",
headers: {"Accept": "application/json;odata=verbose"},
success: function(data){
Data = data.d.results; //global variable that I want to pass.
console.log(Data);
},
error: function(data){
console.log("something is not right with - ", data)
}
});
This is the controller that I would like to pass Data
to. 这是我想将Data
传递给的控制器。
var app = angular.module("contactApp",[]);
app.value('listData', Data);
app.controller('ContactController',['listData','$scope','$http',function(listData,$scope,$http){
console.log(listData);
//Do something here...
});
I'm trying to use value()
but getting an error if I pass in anything other than a string. 我正在尝试使用value()
但是如果我传入的不是字符串,则报错。 So if Data = "Sometext"
it would console out that text but if it's an object it doesn't work. 因此,如果Data = "Sometext"
,它将消除该文本,但是如果它是一个对象,它将无法正常工作。 Not sure what I'm doing wrong but is there a better way of doing this!? 不知道我在做什么错,但是有更好的方法吗?
Yup as Rafael has mentioned try using the $http service from Angular 就像Rafael提到的那样,请尝试使用Angular的$ http服务
https://docs.angularjs.org/api/ng/service/$http https://docs.angularjs.org/api/ng/service/$http
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.