[英]angularjs - directive doesnt work in function
我嘗試使用angular指令,如果我將其正常放置到js文件中,它將正常工作,但是如果我嘗試將其用於功能,它將不起作用:
function getCity(city){
document.getElementById("weather").innerHTML=city;
$.get('https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="' + city + '")&format=json', function (data) {
humi = data.query.results.channel.atmosphere.humidity;
});
var app = angular.module("weatApp", []);
app.directive("humiGet", function() {
return {
template : [humi]
};
});
}
調用指令時可能未設置humi:
function getCity(city){
document.getElementById("weather").innerHTML=city;
$.get('https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="' + city + '")&format=json', function (data) {
humi = data.query.results.channel.atmosphere.humidity;
var app = angular.module("weatApp", []);
app.directive("humiGet", function() {
return { template : [humi] };
});
});
}
更好的方法是使用Promises :
function getCity(city){
document.getElementById("weather").innerHTML=city;
var deferred = $.Deferred();
$.get('https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="' + city + '")&format=json', function (data) {
humi = data.query.results.channel.atmosphere.humidity;
var app = angular.module("weatApp", []);
app.directive("humiGet", function() {
return { template : [humi] };
});
deferred.resolve(true);
});
return deferred.promise();
}
// else where
getCity('Fargo').then(function () {
// use directive here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.