2016-04-24 124 views
0

在我的控制器中,我有一个$ http调用,它返回一个json字符串,然后我要将它传递给要添加到地图的指令。该字符串正在从控制器传递到指令罚款,但不是从控制器中的$ http函数传递到指令。将范围数据从函数传递给父范围?

wmm.controller('wapMapClr', ['$rootScope', '$scope', '$window', '$http', function ($rootScope, $scope, $window, $http) { 

$scope.geobj = {}; 
$scope.geobj.geoprop = "" 

// Search by postcode 
// create a blank object to hold our form information 
$scope.formData = {}; 
$scope.pcSearch = function() { 
$scope.data = {}; 

$http.post('api/api.php', { postcode: $scope.formData }) 
    .success(function (result) { 

     $scope.geobj = {geoprop : result.json_string}; 
     console.log($scope.geobj.geoprop); 

任何帮助将非常感激。由于

+0

你得到任何错误? – Thalaivar

+0

嗨,我没有得到任何错误 - 只是空的字符串。 – Robert

回答

1

Promises是异步的,所以你不知道什么时候promise回报,所以它不会立即为您提供

  1. 您的指令有一个controller方法,从那里你可以解雇$http您可以访问的电话。

  2. 您可以使用$emit/$brodcast来收听从您的指令controller传递的事件。

我不知道你会得到什么样的错误,这里是$timeout使用的小提琴是async其中工程。

var myApp = angular.module('myApp',[]); 

myApp.directive('passObject', function() { 
    return { 
     restrict: 'E', 
     scope: { obj: '=' }, 
     template: '<div>Hello, {{obj.prop}}!</div>' 
    }; 
}); 

myApp.controller('MyCtrl', function ($scope, $timeout) { 
    $scope.obj = { prop: "world" }; 
    $timeout(function(){ 
     $scope.obj = { prop: "from timeout" }; 
    },10000); 
}); 

https://jsfiddle.net/jt6j82by/

0

感谢Thalaivar。我修改了你提供的代码并且工作。请看下图:

wmm.controller('wapMapClr', ['$scope', '$window', '$http', function ($scope, $window, $http) { 

$scope.geobj = {}; 

// Search by postcode 
// create a blank object to hold our form information 
$scope.formData = {}; 
$scope.pcSearch = function() { 
$scope.data = {}; 

$http.post('api/api.php', { postcode: $scope.formData }) 
    .success(function (result) { 

     $scope.geobj = {geoprop : result.json_string}; 

然后在指令...

wmm.directive('tchOlMap', function() { 

    var MAP_DOM_ELEMENT_ID = 'tchMap'; 

    return { 

     restrict: 'E', 
     //BELOW IS THE LINE I CHANGED TO MAKE IT WORK! 
     scope: false, 
     replace: true, 
     template: '<div id="' + MAP_DOM_ELEMENT_ID + '" class="full-height"></div>', 

     link: function postLink(scope, element, attrs) { 
相关问题