【问题标题】:Why are some of my Angular JS data bindings not working?为什么我的一些 Angular JS 数据绑定不起作用?
【发布时间】:2017-06-24 03:31:10
【问题描述】:

我正在将一个网站重写为 Angular JS 1.5.7,但代码不适用于某些数据绑定。

数据在我第一次启动服务器并提供文件时绑定,但如果我重新加载它不再适用于 {{currentWeather.temperature}}

这里是 HTML 和 JavaScript 条目。请注意,我已删除 API 密钥,但在我的本地环境中,console.log() 将显示预期数据,因此我知道 API 工作正常。

HTML:

<!DOCTYPE html>

<html style="background-color:#111111">

<head>
    <title>Your Local Weather</title>
    <link type="text/css" rel="stylesheet" href="css/stylesheet.css">
    <link type="text/css" rel="stylesheet" href="vendors/bootstrap/dist/css/bootstrap.css">
    <link type="text/css" rel="stylesheet" href="css/weather-icons.css">
    <script src="vendors/angular/angular.js"></script>
    <script src="vendors/jquery/dist/jquery.min.js"></script>
    <script src="app/app.js"></script>
</head>

<body ng-app="localWeather" class="body">
    <h1 class="text-primary" id="text-primary-custom" style="text-align: center">Your Local Weather</h1>


    <div ng-controller="MainController">
        <p> {{ userAddress.results[2].formatted_address }}
        </p>

        <p>{{currentWeather.temperature}}</p>


    </div>




    <footer>
        <div class="copyright">Copyright 2017, David Taylor Jr.</div>
        <div class="darksky">
            <p>Weather Data provided by <a href="https://darksky.net/dev">Dark Sky</a> <img src="assets/images/darkskylogo.png" alt="Dark Sky Logo" height="28" width="28"></p>
        </div>
    </footer>
</body>

</html>

JavaScript:

var app = angular.module('localWeather', []);


var MainController = function($scope, $http) {

    var onAddressComplete = function(address) {
        $scope.userAddress = address.data;

    };

    function success(pos) {
        var crd = pos.coords;
        $scope.coords = crd;

        $http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + crd.latitude + ',' + crd.longitude + '&key=API-KEY')
            .then(onAddressComplete);


        $.ajax({
            url: 'https://api.darksky.net/forecast/API-KEY/' + crd.latitude + ',' + crd.longitude + "?units=us",
            dataType: "jsonp",
            success: function(data) {
                $scope.currentWeather = data.currently;
                console.log($scope.currentWeather);
            }
        });

    }

    navigator.geolocation.getCurrentPosition(success);
};


app.controller('MainController', MainController);

这是 console.log 数据:

Object { time: 1486433921, summary: "Mostly Cloudy", icon: "partly-cloudy-night", nearestStormDistance: 30, nearestStormBearing: 278, precipIntensity: 0, precipProbability: 0, temperature: 56.48, apparentTemperature: 56.48, dewPoint: 41.27, 7 more… }

【问题讨论】:

  • 发布console.log数据(数据)
  • 当您刷新先生时,您的console.log($scope.currentWeather); 是否正常工作?
  • @Sajeetharan 我添加了 console.log 数据
  • @pryxen 是的,它每次都会正确记录数据。

标签: javascript html angularjs


【解决方案1】:

由于 AngularJs 脏检查的工作原理,我不相信它会知道您的 $.ajax 调用已返回并更改了 $scope 上的数据。它有时可以工作然后不工作的原因是因为两个同时调用返回的顺序。

如果$http 调用在$.ajax 调用之后返回,Angular 将运行其摘要循环并将所有$scope 值重新绑定到模板,包括在$.ajax 调用中更改的值。相反的场景,$.ajax 返回第二个不会触发这个摘要循环,因为 jQuery 是 Angular 世界的“外部”。

请参阅this solution 了解如何将 jQuery 与 Angular 结合使用。

基本上你想在你的success函数结束时调用$scope.$apply();。请参阅 AngularJs 存储库中有关该主题的 AngularJs docsthis FAQ

$.ajax({
    url: "...",
    dataType: "jsonp",
    success: function (data) {
        $scope.currentWeather = data.currently;
        console.log($scope.currentWeather);
        $scope.$apply();
    }
});

【讨论】:

  • 这实际上只是控制台:Uncaught TypeError: $scope.apply is not a function at Object.success (app.js:25) at i (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at A (jquery.min.js:4) at HTMLScriptElement.c (jquery.min.js:4) at HTMLScriptElement.dispatch (jquery.min.js:3) at HTMLScriptElement.q.handle (jquery.min.js:3)
  • $scope.$apply。 @davidtaylorjr
  • 谢谢@yibuyisheng!糟糕的复制面食。更新了我的答案。
【解决方案2】:

不要使用 jQuery 的 ajax 方法发送请求,而是使用 AngularJS 的 $http 对象。

AngularJS 不会偶尔检查范围数据。所以如果不使用 AngularJS 的 API 做一些异步操作,AngularJS 是无法发现范围数据何时发生变化的。当然你可以使用 AngularJS 的$apply 方法强制使用范围数据更新视图,但这里不推荐。

【讨论】:

  • 我首先使用了 $http 对象,但是,我不断遇到 CORS 问题,无法弄清楚如何解决该问题。你对此有什么见解吗?
  • 这又是一个问题:跨域。有一些解决方案。在您的情况下,您可以在服务器代码的响应中添加 CORS 标头。关于 CORS 标头,请参见此处:developer.mozilla.org/en/docs/Web/HTTP/Access_control_CORS
  • 我实际上已经通读了几次,但似乎无法理解它。我似乎也找不到任何好的教程。为什么 .ajax 方法有效而不是 $http?
  • 哦,你用ajax发送jsonp请求,我之前没注意到。所以,你应该试试$http.jsonp 方法。 @davidtaylorjr
  • 当第三方脚本加载到您的页面时,它可以做很多坏事,很难限制脚本不做坏事。所以很危险,AngularJS提醒你确保第三方资源是安全的。
猜你喜欢
  • 2017-02-22
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
  • 1970-01-01
  • 2016-10-23
  • 2015-06-24
  • 2016-09-26
相关资源
最近更新 更多