在this forum post中提出了类似的问题,但我仍然无法将代码从JSfiddle转换为HTML。
可以找到JSfiddle示例here。
我尝试使用前面提到的论坛帖子中建议的技术,即:
<html>
<head>
<style type="text/css">
// CSS Content
</style>
</head>
<body ng-app="myApp">
<!-- some html elements -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script language="JavaScript" type="text/javascript">
// more js here.
</script>
</body>
由于我是一个完整的菜鸟,我只是将HTML和Javascript复制到某些html元素和 //更多js 这里。在不更改API密钥的情况下,最终代码如下所示:
<html>
<head>
<style type="text/css">
// CSS Content
</style>
</head>
<body ng-app="myApp">
<div ng-app="myapp" ng-controller="WeatherCtrl">
<h2>Weather in Salzburg, Austria</h2>
<weather-icon cloudiness="{{ weather.clouds }}"></weather-icon>
<h3>Current: {{ weather.temp.current | temp:2 }}</h3>
min: {{ weather.temp.min | temp }}, max: {{ weather.temp.max | temp }}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script language="JavaScript" type="text/javascript">
'use strict';
var myapp = angular.module('myapp', []);
myapp.factory('weatherService', function($http) {
return {
getWeather: function() {
var weather = { temp: {}, clouds: null };
$http.jsonp('http://api.openweathermap.org/data/2.5/weather?q=Salzburg,at&units=metric&callback=JSON_CALLBACK&APPID=f9dbd911bc01df1d9ce563b2ba4d3209').success(function(data) {
if (data) {
if (data.main) {
weather.temp.current = data.main.temp;
weather.temp.min = data.main.temp_min;
weather.temp.max = data.main.temp_max;
}
weather.clouds = data.clouds ? data.clouds.all : undefined;
}
});
return weather;
}
};
});
myapp.filter('temp', function($filter) {
return function(input, precision) {
if (!precision) {
precision = 1;
}
var numberFilter = $filter('number');
return numberFilter(input, precision) + '\u00B0C';
};
});
myapp.controller('WeatherCtrl', function ($scope, weatherService) {
$scope.weather = weatherService.getWeather();
});
myapp.directive('weatherIcon', function() {
return {
restrict: 'E', replace: true,
scope: {
cloudiness: '@'
},
controller: function($scope) {
$scope.imgurl = function() {
var baseUrl = 'https://ssl.gstatic.com/onebox/weather/128/';
if ($scope.cloudiness < 20) {
return baseUrl + 'sunny.png';
} else if ($scope.cloudiness < 90) {
return baseUrl + 'partly_cloudy.png';
} else {
return baseUrl + 'cloudy.png';
}
};
},
template: '<div style="float:left"><img ng-src="{{ imgurl() }}"></div>'
};
});
</script>
</body>
我的输出如下:
有人可以告诉我该怎么做吗?
答案 0 :(得分:1)
问题在于您宣布两个应用从正文<body>
标记中删除“ng-app =”myApp“。