为什么AngularJS的服务不绑定到作用域?
Why doesn't AngularJS service bind to scope?
Angular新手试图使用Angular 1.2.21逐字逐句地学习这个地理定位示例。浏览器调试器显示,当GPS触发时,服务位置对象被更新,但范围myords仍然未定义。我试过在几个地方添加$apply,这导致应用正在进行中。这里有什么问题,我需要阅读哪些概念?
angular
.module('myApp', ['ngGeolocation'])
.controller('geolocCtrl', ['$geolocation', '$scope', function($geolocation, $scope) {
$geolocation.watchPosition({
timeout: 60000,
maximumAge: 250,
enableHighAccuracy: true
});
$scope.myCoords = $geolocation.position.coords; // not updated
$scope.myError = $geolocation.position.error; // this becomes truthy, and has 'code' and 'message' if an error occurs
}]);
$geolocation.position
的coords
属性在每次更新时被重新分配。这是position object of
$geolocation '保持不变。
所以,(基于你想如何使用它)你应该这样写:
$scope.myPosition = $geolocation.position;
<!-- If you want to use it in the VIEW -->
<p>Latitude: {{myPosition.coords.latitude}}</p>
<p>Longtitude: {{myPosition.coords.longtitute}}</p>
<p ng-show="myPosition.error">
Error ({{myPosition.error.code}}): {{myPosition.error.message}}
</p>
/* Or if you want to manually $watch for changes in coords */
$scope.$watch('myPosition.coords', function (newValue, oldValue) {...}, true);
相关文章:
- 将作用域绑定到事件处理程序,但保留原始参数
- 将回调绑定到没有隔离作用域的指令
- 隔离作用域+绑定名称和仅在AngularJS中的隔离作用域之间的差异
- 通过json动态绑定作用域到ng模型
- 为什么Angular 1.5双向绑定在将作用域变量传递给组件绑定时失败
- 修改作用域变量后,未更新作用域绑定
- AngularJS$作用域包括我的绑定变量,但以后仍然无法访问,为什么
- AngularJS:图片上传+文件阅读器预览.控制器、指令和作用域之间的绑定出现问题
- 将内部作用域变量绑定到外部“模板”
- 角度指令作用域绑定在 ng-repeat中不起作用
- 将 http GET 响应与 ngRepeat 中的隔离作用域绑定
- 在 $scope.$watch 中更新时,独立作用域绑定不起作用
- 从作用域绑定的动态控制器
- 工厂中与控制器作用域绑定的已修改数据不会更新
- dom内部的指令作用域绑定不起作用
- Angular js用全局作用域绑定局部数组
- 如何使用interval将angular作用域绑定到web worker的结果
- 在角树控件中将数据从父作用域绑定到节点中的元素
- 角作用域绑定
- Javascript自定义作用域绑定函数