简体   繁体   中英

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. Below is what I'm working with:

Getting the data before DOM loads and save it in the Data variable.

    $.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.

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. So if Data = "Sometext" it would console out that text but if it's an object it doesn't work. 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

https://docs.angularjs.org/api/ng/service/$http

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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