我尝试使用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]
};
});
}
答案 0 :(得分:0)
在您致电指令时可能无法设置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
});