简体   繁体   English

函数内部变量的Angularjs范围

[英]Angularjs Scope of Variable inside of function

Following structure inside my HTML: HTML内的以下结构:

<div class="form-group">
  <label for="anbieter">Anbieter</label>
  <input type="text" ng-model="fields_answers.address" class="form-control">
</div>

I want to fill in data from my database with a $http.get inside my controller which looks like the following (only the important stuff): 我想用控制器中的$http.get来填充数据库中的数据,该外观如下所示(仅是重要的内容):

(function(){
var SubmitFormController = angular.module('bdb').controller('submitFormCtrl', ['$scope', '$window', '$location', '$http', '$sce', function($scope, $window, $location, $http, $sce){
    var submitForm = this;
    $scope.fields_answers = {};

    submitForm.showResult = function(){
      $http.get("api/administration/idSearch/" + document.getElementById('searchFieldId').value, true).success(function (response) {
        $scope.fields_answers.address = response[0][0].address;
      });
    };
}());

So when I try to set something with $scope.fields_answers.address outside of the showResult() function it works, but I can't seem to access the ng-model variable inside the showResult function, it doesn't seem to be visible. 因此,当我尝试在showResult()函数之外使用$ scope.fields_answers.address进行设置时,它可以工作,但是我似乎无法访问showResult函数中的ng-model变量,因此它似乎不可见。

Edit : I've tried adding an id="address" to the input and set it inside the showResult() function with 编辑 :我尝试将id =“ address”添加到输入中,并在showResult()函数中进行设置

 document.getElementById('address').value = response[0][0].address;

this works . 这有效 But I want ( have ) to use the ng-model variable. 但是我想( 必须 )使用ng-model变量。

I'm not sure if this is related to your issue or not, but the use of success on $http.get is deprecated. 我不确定这是否与您的问题有关,但是不建议在$ http.get上使用成功。 Try changing success to then. 尝试将成功更改为那时。

Then returns a full response object so your data should be on the data member of the response meaning you would access it with response.data and then usually when there are multiple values they will be in a values array off of data, so probably response.data.values[0][0].address. 然后返回一个完整的响应对象,因此您的数据应位于响应的数据成员上,这意味着您将使用response.data访问它,然后通常当存在多个值时,它们将位于数据数组之外,因此可能是响应。 data.values [0] [0] .address。

If that's a bit off, output response to the console and adjust accordingly and if necessary, post what the response object looks like here. 如果有点不对劲,则将响应输出到控制台并进行相应调整,如有必要,请在此处发布响应对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM