【问题标题】:Two way binding of a model in a directive does not work指令中模型的两种方式绑定不起作用
【发布时间】:2015-11-03 20:22:13
【问题描述】:

基于another question from me 的评论,我尝试创建一个指令来减少我的代码。这是我得到的:

指令(测试用的很小,以后会有更多的元素):

BebuApp.directive('inputText', function(){
    return {
        restrict: 'E',
        scope: {
            model: '='
        },
        template: '<input type="text" ng-model="model" />'
    }
});

状态:

.state('app', {
            abstract: true,
            url: '',
            templateUrl: 'layout.html',
            resolve: {
                authorize: function ($http) {
                    return $http.post(API.URL_PING); 
                }
            }
        })
.state('app.application-detail', {
            url: "/bewerbungen/{id}",
            templateUrl: "views/application-detail/application-detail.html",
            data: {pageTitle: 'Meine Bewerbungen', pageSubTitle: ''},
            controller: "ApplicationDetailController",
            resolve: {
                prm: function ($http, $stateParams) {
                    // $http returns a promise for the url data
                    return $http.get(API.URL_JOBAPPLICATION_GET_DETAILS + "/" + $stateParams.id);
                }
            }
        })

控制器:

'use strict';

BebuApp.controller('ApplicationDetailController', function($rootScope, $scope, $http, $stateParams, API, prm) {
    $scope.jobApplication = prm.data;
    console.log(prm);

    $scope.$on('$viewContentLoaded', function() {
        // initialize core components
        App.initAjax();    
    });
});

模板/视图:

<div class="margin-top-10">
{{ jobApplication }}
    <input-text model="jobApplication.description"></input-text>

</div>

加载页面后,我可以看到正确的模型({{jobApplication}} 输出),但输入字段为空。我需要一个正常的双向绑定。当模型在范围内发生变化时,它也应该在指令中发生变化,反之亦然。据我了解,模型是由状态下的解析回调/函数检索的,因此在编译模板时它应该在“那里”。

我的问题在哪里?

【问题讨论】:

  • 在指令范围定义中尝试使用 ngModel 而不是 model scope: { ngModel: '=' }
  • 您能否将{{jobApplication}} 的输出添加到您的问题中?
  • 这是您的代码的精简版本,其中包括我们需要的所有内容,除了{{jobApplication}} 的输出。我们需要知道 json 对象的格式和数据才能诊断问题。 plnkr.co/edit/LA45iEiIh4vBPFyOxrSB?p=info
  • 谢谢你们!在您的 cmets 之后,我仔细查看了模型(第三次),但现在我发现了问题。看我的回答。

标签: angularjs angularjs-directive angularjs-scope angular-ui-router


【解决方案1】:

我在仔细查看模型后发现了问题(感谢 cmets!)。事实上,我从后端收到的模型是一个只有一个条目的集合。它看起来像这样:

[{id:"xxx", description:"test".....}]

当然它必须是这样的:

{id:"xxx", description:"test"...}

修复这个愚蠢的错误后,一切正常!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    相关资源
    最近更新 更多