2

我有一個控制器,它調用執行$ http.get更新指令範圍後,控制器服務呼叫

app.controller('myController', function ($scope, mService) { 

    $scope.chair; 

    myService.getData().then(function (data) { 
     $scope.chair = data.chairID; 
    }); 

}); 

內的控制器範圍的服務,我有我正努力的指令通過在$ scope.chair值:

<section ng-controller="mycontroller"> 

    <my-directive data-chair="chair"></my-directive> 

</section> 

並在myDirective.js

restrict: 'E', 
replace: true, 
templateUrl: 'app/some-file.html', 
scope: { 
    chair: '=' 
}, 
controller: [ '$scope', function ($scope) { 
    alert('got chair : ' + $scope.chair); 
    .... 

但是,通過上述,我發現警告時('got chair:'+ $ scope.chair)未定義。

內位指示,如果我硬編碼的椅子:

app.controller('myController', function ($scope, mService) { 

    $scope.chair = 'hello'; 

    myService.getData().then(function (data) { 
     $scope.chair = data.chairID; 
    }); 

}); 

我的指令將顯示hello

+1

您使用的是哪個版本的Angular? – Makoto

+0

使用v1.4.0感​​謝 –

回答

0

這應該工作:

.directive('myDirective', function() { 
    return { 
    restrict: 'E', 
    replace: true, 
    templateUrl: 'app/some-file.html', 
    scope: { 
     chair: '=' 
    }, 
    link: function(scope, element, attrs) { 
     alert('got chair : ' + scope.chair); 
    } 
    } 
}); 
+0

謝謝,但我需要在控制器內訪問它,而不是鏈接 –

1

「主席」內部變量可能不會被當您嘗試訪問它的指令集。它似乎也是通過服務異步加載的。

您需要在指令中附上手錶。您傳遞給手錶的回調將在「主持人」範圍變量值更改後的下一個角度$摘要階段中調用。

... 
controller: [ '$scope', function ($scope) { 
    $scope.$watch('chair', function(chairValue) { 
     if (chairValue === undefined) return; 

     // There is a value. 
     alert('got chair : ' + $scope.chair); 
    }); 
}] 

此代碼將導致每次值更改時調用回調。

如果您不想處理更改值,請在值穩定後清除手錶(與未定義的不同)。如果您有許多綁定和手錶的複雜視圖,這將會帶來更好的性能。

... 
controller: [ '$scope', function ($scope) { 
    var unwatch = $scope.$watch('chair', function(chairValue) { 
     if (chairValue === undefined) return; 

     // There is a value. 
     alert('got chair : ' + $scope.chair); 
     unwatch(); 
    }); 
}]