简体   繁体   English

Angular ng-model 未绑定到输入字段

[英]Angular ng-model not binding to input fields

I have the following controller working and I can use ng-repeat to display the ONE json object I have.我有以下控制器工作,我可以使用 ng-repeat 来显示我拥有的一个 json 对象。 I just used ng-repeat to make sure the data was actually coming across.我只是使用了 ng-repeat 来确保数据确实出现了。 But I can't figure out how to bind my input fields to show the data inside the text fields in this edit view/template.但我不知道如何绑定我的输入字段以显示此编辑视图/模板中文本字段内的数据。

Controller控制器

angular
    .module("renderIndex", ["ngRoute","ngCookies"])
    .config(config)
    .controller("favoritesController", favoritesController)
    .controller("newFavoriteController", newFavoriteController)
    .controller("editFavoriteController", editFavoriteController);

function config($routeProvider) {
    $routeProvider

        //...left out for brevity

        .when("/editfavorite/:searchId", {
            templateUrl: "/ng-js/ng-templates/editFavoriteView.html",
            controller: "editFavoriteController",
            controllerAs: "vm"
        })
        .otherwise({ redirectTo: "/" });
};

//...left out for brevity

function editFavoriteController($http, $window, $routeParams) {
    var vm = this;
    vm.search = [];

    var url = "/api/favorites/" + $routeParams.searchId;
    $http.get(url)
        .success(function (result) {
            vm.search = result;
        })
        .error(function () {
            alert('error/failed');
        })
        .then(function () {
            //Nothing
        });
};

The controller works, it accepts a parameter of id and that is is used and tacked onto the end of the api endpoint URL.控制器工作,它接受一个 id 参数,该参数被使用并附加到 api 端点 URL 的末尾。 I get back a good response that is one json object, I am able to pass that over to the view using vm.search and if you notice at the bottom of the view I have a ng-repeat (which is only there because I wanted to make sure that some data was actually coming over the wire and it is. Of course it only repeats one record because this is an edit page, but it works, but my binded inputs are not showing anything in the text fields when the view renders. This has to be something simple, can anyone help?我得到了一个很好的响应,它是一个 json 对象,我可以使用vm.search将其传递给视图,如果您注意到视图底部有一个ng-repeat (这只是因为我想要以确保某些数据实际上是通过网络传输的。当然它只重复一条记录,因为这是一个编辑页面,但它可以工作,但是当视图呈现时,我的绑定输入未在文本字段中显示任何内容. 这必须是一些简单的事情,有人可以帮忙吗?

EditView/Angular Template编辑视图/角度模板

<div class="small-12 column"><h3>Edit Search</h3></div>
<div class="small-12 column">
    <form name="editFavoriteForm" novalidate ng-submit="vm.update()">
        <input name="userId" type="hidden" ng-model="search.userId" />
        <label for="name">Name</label>
        <input name="name" type="text" ng-model="vm.search.name" />
        <label for="description">Description</label>
        <textarea name="description" rows="5" cols="30" 
                  ng-model="vm.search.description"></textarea>
        <input type="submit" class="tiny button radius" value="Save" /> | 
        <a href="#/" class="tiny button radius">Cancel</a>
    </form>
</div>
<div data-ng-repeat="s in vm.search">
    <p>{{s.name}} - {{s.userId}}</p>
</div>

So just to reiterate.... Data is being sent over in vm.search and it is the one database record that I am expecting, I know it is because it displays when I use ng-repeat .所以只是重申.... 数据正在vm.search中发送,这是我期望的一个数据库记录,我知道这是因为它在我使用ng-repeat时显示。 But when I use ng-model='vm.search.name' I don't get the data bound to the field so that I can edit it.但是当我使用ng-model='vm.search.name'我没有将数据绑定到该字段,以便我可以对其进行编辑。 Can anyone point out what I am doing wrong?谁能指出我做错了什么?

As you can see below I put some test data in and went to the edit page for that item, name=asdf & userId=fec87a96-22d7-4e8c-8991-fa01df60c5c0.正如您在下面看到的,我放入了一些测试数据并转到了该项目的编辑页面,name=asdf & userId=fec87a96-22d7-4e8c-8991-fa01df60c5c0。 Which are both expected values, but nothing shows up in the bounded text fields using the same vm.search model.这两个都是预期值,但在使用相同 vm.search 模型的有界文本字段中没有显示任何内容。

在此处输入图片说明

The answer was pretty simple here, thanks to Phil.在这里,答案非常简单,感谢 Phil。 First off I should not have been using ng-repeat at the bottom of my code as a way of testing to see if my values were there, it is much better to use something like:首先,我不应该在我的代码底部使用ng-repeat作为测试我的值是否存在的一种方式,最好使用以下内容:

 <pre>{{ vm.search | json }}</pre>

This spits out (in a code view) the actual json object that is being held in vm.search and the | json这会(在代码视图中)吐出vm.search中保存的实际 json 对象和| json | json appended after the variable name just helps to format the json out on the page.附加在变量名称之后的| json只是有助于在页面上格式化 json。 If you did not use it you would just see everything on one line.如果您不使用它,您只会在一行上看到所有内容。 So again @Phil, thank you for the tip!再次@Phil,感谢您的提示!

One thing I wasn't realizing is that my result from the http.get call which I was stuffing into the vm.search variable.有一件事我没有意识到的是,我的resulthttp.get调用这让我塞进了vm.search变量。 Is actually an array.实际上是一个数组。 OBVIOUSLY you say, but it didn't dawn on me to only grab the first item from that array and stuff that in my variable named vm.search instead I was doing this:显然你说,但我并没有意识到只从该数组中获取第一项以及我的名为vm.search变量中的内容,而不是我这样做:

$http.get("/api/favorites")
.success(function (result) {
    vm.searches = result;
})

When in fact I should have been doing this:事实上,我应该这样做:

$http.get("/api/favorites")
.success(function (result) {
    vm.searches = result[0];
})

Now to look at the difference let's save out the result that we get from现在看看不同之处,让我们保存我们得到的结果

 <pre>{{ vm.search | json }}</pre>

using each method, first without targeting the first array element, we get:使用每种方法,首先不针对第一个数组元素,我们得到:

[
  {
    "searchId": 91,
    "userId": "fec87a96-22d7-4e8c-8991-fa01df60c5c0",
    "name": "xxx123",
    "description": "123xxx",
    "created": "2015-03-11T01:12:37.32",
    "searchString": "/?"
  }
]

Now if we extract the result using the latter method, going straight for the first element result[0] we get the results as an object, not an object contained within an array of only one item.现在,如果我们使用后一种方法提取结果,直接获取第一个元素result[0]我们将得到作为对象的结果,而不是包含在只有一个项目的数组中的对象。

{
  "searchId": 91,
  "userId": "fec87a96-22d7-4e8c-8991-fa01df60c5c0",
  "name": "xxx123",
  "description": "123xxx",
  "created": "2015-03-11T01:12:37.32",
  "searchString": "/?"
}

I know this seems tedious to explain all of this, but for someone like me who overlooked it, this is the difference between your model binding or not binding to the input values for each text field and even though it's very simple it's very possible that other noobs like myself would overlook this.我知道解释所有这些似乎很乏味,但是对于像我这样忽略它的人来说,这是模型绑定或不绑定到每个文本字段的输入值之间的区别,尽管它非常简单,但很可能其他像我这样的菜鸟会忽略这一点。 I'm sure someone could better explain exactly what the difference is between the two.我相信有人可以更好地解释两者之间的区别。

Feel free ANYONE to edit my answer and better explain, especially if it takes less lines of code to do so!任何人都可以随意编辑我的答案并更好地解释,特别是如果这样做需要更少的代码行!

The way controller and view talk to each other is through $scope.控制器和视图相互通信的方式是通过 $scope。 In your case the controller's vm variable is local to controller and is not available to view as you are declaring it as var vm .在您的情况下,控制器的 vm 变量是控制器的本地变量,并且在您将其声明为var vm无法查看。

When you access vm in view, it actually creates a new variable vm and put it on scope.当您在视图中访问 vm 时,它实际上会创建一个新变量 vm 并将其放在作用域中。

To correct it you need to pass $scope as controller dependency and use $scope.vm in your controller.要纠正它,您需要将 $scope 作为控制器依赖项传递并在控制器中使用 $scope.vm 。 Your controller should look like:您的控制器应如下所示:

function editFavoriteController($scope, $http, $window, $routeParams) {
    $scope.vm.search = [];

    var url = "/api/favorites/" + $routeParams.searchId;
    $http.get(url)
        .success(function (result) {
            $scope.vm.search = result;
        })
        .error(function () {
            alert('error/failed');
        })
        .then(function () {
            //Nothing
        });
};

With these your view and controller should now refer to same 'vm' variable available in $scope.有了这些,您的视图和控制器现在应该引用 $scope 中可用的相同“vm”变量。

Please note that you need not to explicitly use $scope.vm in your view as 'vm' is implicitly refers to $scope.vm in view.请注意,您无需在视图中显式使用 $scope.vm,因为 'vm' 在视图中隐式引用 $scope.vm。

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

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