将范围数据从函数传递到父范围?

时间:2016-04-24 21:20:57

标签: angularjs angularjs-scope

在我的控制器中,我有一个$ 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);

任何帮助都会非常感激。感谢

2 个答案:

答案 0 :(得分:1)

Promises是异步的,因此您不知道promise何时返回,因此无法立即为您提供

  1. 您的指令采用controller方法,您可以从中触发可以访问的$http来电。

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

  3. 我不确定你得到了什么错误,这里有$timeout使用的async小提琴,它有效。{/ p>

    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/

答案 1 :(得分: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) {