Angular自定义指令函数传递的参数没有绑定

时间:2015-07-02 12:06:22

标签: angularjs angularjs-directive

enter image description here

我正在实施一篇文章/评论页面。在文章页面中,将有一个文章部分,一个评论列表和一个评论创建部分。

我有一个自定义指令myComment,其中包含titlecontent <input>以及1提交<button>,就像youtube页面一样。

在article_view的控制器中,我有一个空的commentInfo对象,将在my_comment目录中分配。然后我调用onCreate函数,该函数绑定到控制器的createComment函数。

问题是commentInfo对象没有被commentInfo = {}清空,在用户输入this is titlethis is content然后点击submit后,您可以看到插入到<div ng-repeat="comment in article.comments"> <my-comment type="view" at="list" entity="comment" on-delete="deleteComment(comment)" on-update="updateComment(comment)"></my-comment> </div> <div> <my-comment type="create" at="list" entity-info="commentInfo" on-create="createComment(commentInfo)"></my-comment> </div> 的评论列表,但评论创建区域仍具有值

一些相关的源代码:

article_view.html

$scope.commentInfo = {}
$scope.createComment = function(commentInfo) {
    var newComment = new Comment({
        title: commentInfo.title,
        content: commentInfo.content,
        articleId: $scope.article._id
    })
    newComment.$save(function(data) {
        $scope.article.comments.push(data)
        commentInfo = {} //todo: input is not cleared after creation
        $scope.success = ['create comments success']
    }, function(err) {
        $scope.error = [err.data.message]
    })
}

article_view.js(在控制器功能中)

app.directive('myComment', ['userService', function(userService) {
    return {
        restrict: 'E',
        scope: {
            type: '@',
            at: '@',

            entity: '=',
            entityInfo: '=',
            onCreate: '&',
            onDelete: '&',
            onUpdate: '&'
        },
        templateUrl: '/public/article/my_comment.html',
        link: function(scope, element, attrs) {
            scope.userService = userService

        }

    }
}])

my_comment.js:

<!--create mode-->
<div ng-show="type === 'create'">

    <input type="text" ng-model="entityInfo.title"/>
    <textarea ng-model="entityInfo.content"></textarea>
    <button ng-click="onCreate(entityInfo)">Create Comment</button>

</div>

my_comment.html

var newModel = {
            CountryCode: $("#CountryCode").val(),
            LanguageCode: $("#LanguageCode").val(),

            PhoneId1: "1",
            PhoneNumber1: $phone1.val(), 
            Extension1: $ext1.val(), 

            PhoneId2: "2",
            PhoneNumber2: $phone2.val(), 
            Extension2: $ext2.val(),

            PhoneId3: "3",
            PhoneNumber3: $phone3.val(), 
            Extension3: $ext3.val(), 

            FirstName: $firstName.val(),
            LastName: $lastName.val() 
        };

        var currentModel = {
            CountryCode: oldModel.CountryCode,
            LanguageCode: oldModel.LanguageCode,

            PhoneId1: "1",
            PhoneNumber1: oldModel.UserPhoneDetail[0].PhoneNumber,
            Extension1: oldModel.UserPhoneDetail[0].Extension,

            PhoneId2: "2",
            PhoneNumber2: oldModel.UserPhoneDetail[1].PhoneNumber,
            Extension2: oldModel.UserPhoneDetail[1].Extension,

            PhoneId3: "3",
            PhoneNumber3: oldModel.UserPhoneDetail[2].PhoneNumber,
            Extension3: oldModel.UserPhoneDetail[2].Extension
        };

        $.ajax(
                {
                    type: "POST",
                    url: apiUrl,
                    dataType: "JSON",
                    contentType: "application/json; charset=utf-8",
                    headers: { "__RequestVerificationToken": token },
                    data: JSON.stringify({ NewModel: newModel, OldModel: currentModel }),
                    cache: false,
                    async: false,
                    success: function (response) {
                        if (response.isSuccess == "False")
                            phoneRegistration.ShowSecondaryAuthentication();
                        else {
                            $("#hdnShowSecondaryAuthentication").val("False");
                        }
                    },
                    error: function (xhr, ajaxOptions, error) {
                        debugger
                        alert(xhr.responseText);
                    }
                });

1 个答案:

答案 0 :(得分:1)

这是双向数据绑定的效果

$ scope.createComment 函数中,在创建 newComment 对象后执行此操作。

      $scope.commentInfo ={}

还有一些建议 -

以下陈述 -

<button ng-click="onCreate(entityInfo)">Create Comment</button>

您无需传递 entityInfo ,因为它通过双向数据绑定传递给指令。

因此,使用 $ scope.commentInfo

$ scope.createComment 功能可以直接使用 entityInfo
var newComment = new Comment({
        title: commentInfo.title,
        content: commentInfo.content,
        articleId: $scope.article._id
    })

可以写成

 var newComment = new Comment({
        title: $scope.commentInfo.title,
        content: $scope.commentInfo.content,
        articleId: $scope.article._id
    })



编辑代码:

  1. 在$ scope.commentInfo中 - commentInfo对象绑定到$ scope.Also你在 my-comment 指令中提到了与 entityInfo 对象的双向数据绑定.So, $ scope.commentInfo entityInfo 指向相同的对象referance.So,如果其中一个更新,它将更新其他。

  2. $ scope.createComment 函数中的 commentInfo 对象中,它是本地对象,并且未绑定到 $ scope 。你还在使用isloated范围。它没有原型继承。因此,该指令不能意外地读取或修改父作用域。由于 commentInfo 未绑定到 $ scope ,因此它甚至不会退出指令的父范围即控制器。此外, commentInfo之间没有定义双向数据绑定 entityInfo 。所以,这些是不同范围内的不同对象,一个是功能范围,一个是指令范围,每个都有自己的副本