我正在創建一個繼承父控制器範圍的自定義指令。大多數情況下,我可以訪問我在控制器的「$ scope」中設置的指令的「範圍」對象,除了我在$ http.get中設置的屬性外。無論這些屬性來自API還是隻是從字面上定義都無關緊要。
對我來說很奇怪的是,如果我只記錄指令的「範圍」,我可以看到由$ http.get設置的屬性,但是如果我嘗試直接訪問它們,它們是未定義的。
我可以完美地訪問HTML視圖中的所有內容。
var myApp = angular.module('myApp');
myApp.controller('getData', function($scope, $http) {
var myData='myData.json';
$scope.helloFromController = "Hello! This is the controller!";
$scope.getTheData = function() {
$http.get(myData).
success(function(data, status) {
$scope.helloFromHttp = "Hello! This is the http!";
});
};
$scope.getTheData();
});
myApp.directive('useData', function ($parse) {
var directiveObj = {
link: function (scope, element, attrs) {
console.log(scope);
// Returns the scope object that clearly includes the helloFromController and helloFromControllerHttp properties
console.log(scope.helloFromController);
// returns "Hello! This is the controller!"
console.log(scope.helloFromHttp)
// returns undefined
}
};
return directiveObj;
});
它看起來像是有$ $作用於$ http,我不明白。幫助表示讚賞。
這不是關於$範圍,它只是事實,即ajax是異步的。 – dfsq