javascript - Angular 代码未显示在 html 页面上

标签 javascript html angularjs scope angularjs-scope

我已经搞了 2 个小时了,找不到解决方案。 下面是显示日志的 chrome 开发工具输出。

(按顺序)

3 - 未定义

1 - 检查

2 - Google 用户

为什么我的 html 中的 place 变量没有更新为“A Google User”?

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

myApp.controller('AppCtrl', ['$scope', '$http', '$log',
  function($scope, $http, $log) {

    var request = {
      placeId: 'ChIJX3piIfJ4j4ARXuQlqgn6LaA' //Walmart HQ
    };

    service = new google.maps.places.PlacesService(map);

    service.getDetails(request, function(place, status) {
      $log.log('1 - check');
      $log.log('2 - ' + place.reviews[0].author_name);
      $scope.place = place.reviews[0].author_name;
   });

    $log.log('3 - ' + $scope.place);
  }
]);

<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <title>Place details</title>
  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>

  <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js'></script>

  <script src="app.js"></script>
</head>

<body>
  <div id="map"></div>
  <div ng-controller='AppCtrl'>

    {{ place }}

  </div>
  </div>


</body>

</html>

最佳答案

google.maps.places.PlacesService 不是内置的异步处理程序,您需要在异步调用后运行 $scope.$apply。使用 $scope.$apply 更新 View :

$scope.$apply(function () {
    $scope.place = place.reviews[0].author_name;
});

更新 1

检查 $apply :

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.

当发生可能更新时,Angular 执行脏检查。 XHR 调用不在范围内。 Angular 不会更新 View ,除非您通过$apply要求它进行脏检查。

最佳实践是:尽可能使用 Angular 内置提供程序,例如 $timeout$http。或 ng-clickng-change 等。这些将隐式调用 $apply

关于javascript - Angular 代码未显示在 html 页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978203/

相关文章:

javascript - 脚本中没有被编译

javascript - dojo 获取 foreach 中当前节点的父节点

javascript - 检查输入是否未禁用且 jquery 不起作用

Javascript 函数每次调用时都不会执行

javascript - 一键禁用窗口 beforeunload 属性

html - CSS 相对定位不起作用

html - 动态创建列表卡angularjs仪表板

jquery - 如何在 OnsenUI 框架中对列表进行分页

javascript - 为什么我不能在 JS 中解析没有引号的 JSON?

javascript - jquery 选择器 - 选择不在另一个嵌套标签内的值