如何将动态变量从javascript分配给angularJS范围

时间:2014-02-27 07:09:06

标签: javascript html angularjs

我有一个表单,用户点击谷歌地图,纬度和经度显示在文本框中。

function addMarker(location) {
  document.getElementById('hLat').value = location.lat().toPrecision(8);
  document.getElementById('hLong').value = location.lng().toPrecision(8);  
}

文本框定义为

<input type="text"  id = "hLat" name = "hLat" ng-model="form.latitude"/>
<input type="text"  id = "hLong" name = "hLong" ng-model="form.longitude"/>

以上述方式,$ scope.formDetails.latitude在控制器中未定义,并收到404错误。虽然纬度和经度值显示在文本框中。

如果我这样做

 document.getElementById('hLat').value = "25.6";
 document.getElementById('hLong').value = "45.6";  

输出为25.6,函数执行成功。

我的控制器定义如下:

var app = angular.module('myApp', []);
app.controller('FormCtrl', function ($scope, $http) {

    $scope.formData = {
        epic: "default"

    };

    $scope.formDetails = {

        latitude: "default",
        longitude: "default"

    };


    $scope.save = function() {
        formData = $scope.form;
    };

        $scope.submitDetails = function() {
        console.log("posting data....");
        $scope.formDetails = $scope.form;
        document.write($scope.formDetails.latitude); // strange behaviour
        $http({method:'GET', url:'http://localhost/nametestjson.php', params:{search_type:"details", latitude:$scope.formDetails.latitude, longitude:$scope.formDetails.longitude, page_no:"1", results_per_page:"15"}}).success(function(data){        
            $scope.friends = data.response.docs;        
            var str = JSON.stringify(data, undefined, 2);       
            alert("success");
        }).error(function(data, status, headers, config) {

            alert(status);
            });           
    };

});

1 个答案:

答案 0 :(得分:0)

我之前几天也有同样的问题

function addMarker(location) {
  document.getElementById('hLat').value = location.lat().toPrecision(8);
  document.getElementById('hLong').value = location.lng().toPrecision(8);  
}

目前你正在使用angularjs,为什么你写了纯javascript编码?请试试这个

function addMarker(location) {
      $scope.form.latitude= location.lat().toPrecision(8);
      $scope.form.longitude= location.lng().toPrecision(8);  
      $scope.$apply();
    }