2
我正在嘗試在AngularJS中使用1.5組件。我有一個服務使用$ HTTP獲取我的JSON文件並返回承諾。然後我解決我的組件控制器中的承諾,並使用this.work
將其分配給控制器上的值。雖然這不會顯示在我的HTML頁面中。如果這是令人困惑的,我在代碼中加入了一些更好的解釋。HTTP獲取Angular 1.5組件
我的理解是,解決承諾(在我的控制器中)是異步發生的,但一旦解決了,爲什麼我沒有在視圖中顯示更新已更改爲變量$ctrl.work
。相反,我從來沒有從變量中獲得一個值。
// Component
(function() {
angular.module('development')
.component('pgDev', {
templateUrl: 'app/development/development.template.html',
controller: ['workList', function (workList) {
//this.work = 'HELLO WORLD'; // <- this shows up in the html if uncommented
workList.getWorkItems().then(function (d) {
console.log(d.test); // outputs: myjsonfile
this.work = d.test; // <- this doesnt show in the html
});
}]
})
}());
// HTTP Get Service
(function() {
angular.module("development").factory("workList", ["$http",
function ($http) {
return {
getWorkItems: function() {
return $http.get("data/worklist/worklist.json").then(function (d) {
return d.data;
});
}
}
}])
})();
// html
workitems: {{$ctrl.work}}
謝謝。如果你知道,或者可以指向正確的方向,那麼使用'this'在控制器中分配內容似乎是有問題的,因爲我不能在函數內部使用'this'分配控制器,因爲正如你在你的答案,這個上下文不會與控制器組件相關。那麼應該怎樣做(而不是使用箭頭函數)? – okayilltry
你可以在開頭保存參考以正確使用'this'並稍後使用它:'const self = this; ... self.work = d.test'。但這是老派。箭頭功能是最純粹的解決方案。 – dfsq