0
我試圖顯示一個變量時,它可用,但它不顯示。 它只顯示當我通過點擊按鈕再次調用函數。 不在我的代碼中使用$ scope。並做了一些(可能)奇怪的事情來嘗試並使其工作。角度模型不更新視圖
任何人都可以弄清楚爲什麼它不會馬上顯示出來嗎?
HTML:
<body ng-app="LocApp">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<info>
</info>
</body>
JS:
angular.module('LocApp', [])
.directive('info', function infoDirective(){
return {
restrict: 'E',
scope: {},
template: '<button ng-click="LocaCtrl.getLoc()">Get location</button><h1>{{LocaCtrl.dif | number:2}}</h1><h3 style="color: red;">{{LocaCtrl.error}}</h3>',
bindToController: {
dif: '<',
error: '<'
},
require: ['info'],
controller: function(){
console.log('test');
var controller = this;
controller.dif = 0;
controller.toRad = function(val){
return val * Math.PI/180;
};
controller.calcDif = function(lat1, lon1){
console.log("Latitude:", lat1);
console.log("Longitude:", lon1);
var lat2 = 52.099233999999996;
var lon2 = 5.0651474;
var R = 6371e3; // metres
var rad1 = controller.toRad(lat1);
var rad2 = controller.toRad(lat2);
var deltRad = controller.toRad(lat2-lat1);
var deltLamb = controller.toRad(lon2-lon1);
var a = Math.sin(deltRad/2) * Math.sin(deltRad/2) +
Math.cos(rad1) * Math.cos(rad2) *
Math.sin(deltLamb/2) * Math.sin(deltLamb/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
controller.getLoc = function(){
navigator.geolocation.getCurrentPosition(function(position) {
let lat1 = position.coords.latitude;
let lon1 = position.coords.longitude;
controller.dif = controller.calcDif(lat1, lon1);
console.log("dif",controller.dif);
}, function(error){
console.log(error);
});
};
},
controllerAs: 'LocaCtrl',
link: function(scope, element, attrs, ctrls){
ctrls[0].getLoc();
}
};
});
我想你還沒有加入。你的指令JS文件在你的HTML文件中 –
它按預期工作看到這個http://plnkr.co/edit/tkoW8Icuam4BEdxmY6En?p=preview –
@VinodLouis它顯示的是初始值,但它沒有用我在開始時運行的函數的新值 – Kuiken