0

Here's a plunkr with my problem: http://plnkr.co/edit/Sx830ekQyP7YBqmRB4Nd?p=preview

Click "Open", then click on "5". Notice how it changes to "test"? Now, type something into Body. It'll either say "Say a little more..." or "Now for the title". Either way, click the button again, and notice how it doesn't change to "test"? Why not? If I remove the directive, the button changes to "test" with or without text in the body.

I know this has to do with the scope in the directive, but I don't understand what exactly is wrong. Can you explain? Thanks.

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);
    }
};
});

1 Answer 1

1

Try to wrap all your variables into an object.

Define $scope.obj = {}; first and change all your scope.submitPostValue to $scope.obj.submitPostValue. In your HTML, change ng-value='submitPostValue' to ng-value=obj.submitPostValue.

Sign up to request clarification or add additional context in comments.

2 Comments

A directive creates it's own scope under its parent scope. When you update a variable in directive, it updates the value in the directive scope. Wrapping variables into an object can avoid this issue because objects are passed by reference.
Thanks, Shawn Song.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.