这是我的问题所在:http://plnkr.co/edit/Sx830ekQyP7YBqmRB4Nd?p=preview

单击“打开”,然后单击“ 5”。请注意它如何变为“测试”?现在,在“正文”中键入一些内容。它会说“多说一声...”或“现在标题”。无论哪种方式,请再次单击该按钮,然后注意它不会变为“测试”吗?为什么不?如果我删除指令,则该按钮将变为“测试”,而正文中有无文本。

我知道这与指令中的范围有关,但是我不明白到底是什么错误。你可以解释吗?谢谢。

angular.module('plunker', ['ngDialog']).controller('MainCtrl', function($scope, ngDialog) {
//$scope.submitPostValue = "OK";

$scope.submitPost = function() {
  $scope.submitPostValue = 'test';
};

$scope.open = function () {
console.log('open');
    $scope.submitPostValue = '5';
            ngDialog.openConfirm({
            template: 'postModal',
            showClose: true,
            trapFocus: false,
            scope: $scope,
        }).then(function (success) {
        }, function (error) {

        });
};
 }).directive('bodyValidator', function () {
return {
    require: 'ngModel',
    link: function (scope, element, attr, ctrl) {
        function customValidator(ngModelValue) {
            if(ngModelValue.length > 0){
                if(ngModelValue.length < 10) {
                    scope.submitPostValue = "Say a little more...";
                    scope.bodyValid = false;
                }
                else {
                    scope.bodyValid = true;
                    if(scope.titleValid)
                        scope.submitPostValue = "Submit";
                    else
                        scope.submitPostValue = "Now for the title..."
                   }
                }
                else {
                scope.submitPostValue = "Enter a body...";
                scope.bodyValid = false;
            }

            return ngModelValue;
        }
        ctrl.$parsers.push(customValidator);
    }
};
});

最佳答案

尝试将所有变量包装到一个对象中。

首先定义$scope.obj = {};,然后将所有scope.submitPostValue更改为$scope.obj.submitPostValue。在HTML中,将ng-value='submitPostValue'更改为ng-value=obj.submitPostValue

09-11 13:49