0

I am trying to make a directive that is basically a text box with a max length counter on it. My directive is below. Basically a text box that will tell the user that they only have x number of characters left.

angular.module('InputApp', []);

angular.module('InputApp').directive('textAreaCounter', function () {
    return {
        templateUrl: '/Content/Directives/Inputs/TextAreaCounter.html',
        restrict: 'AE',
        multiElement: true,
        scope: {
            text: '='
        },
        link: function (scope, elem, attrs) {
            if (scope.text == undefined || scope.text == '') {
                scope.CharactersLeft = attrs.totalCharacters;
            } else {
                scope.CharactersLeft = attrs.totalCharacters - scope.text.length;
            }

            scope.TextValueChanged = function () {
                scope.CharactersLeft = attrs.totalCharacters - scope.text.length;
            }
        }
    }
});

The template html is:

<div class="row">
    <div class="col-md-12">
        <textarea ng-model="text" ng-change="TextValueChanged()" autogrow rows="5"></textarea>
    </div>
</div>
<div class="row">
    <div class="col-md-12 top-left smallText">
        You have {{CharactersLeft}}.
    </div>
</div>

And I use the directive like this.

<text-Area-Counter text="WholeDeletionText" total-Characters="250"></text-Area-Counter>

The issue that I am having is that the value 'WholeDeletionText' is not being updated by the directive.

My expectation is that the scope.WholeDeletionText in the parent would update with the text that was written in the textarea in the directive. At least my understanding of the isolated scope having the '=' sign is that they share it with the parent. What am I doing wrong or is there a better way to do it?

2 Answers 2

1

The problem occurs because you have not WholeDeletionText variable in the application scope.

To fix it you need:

1) create controller and initialize WholeDeletionText variable

.controller("MyController", function ($scope) {
    $scope.WholeDeletionText = '123';
});

2) add ng-controller="MyController" directive in your main html file.

<body ng-app="InputApp" ng-controller="MyController">
<div>
    <text-Area-Counter text="WholeDeletionText" total-Characters="250"></text-Area-Counter>
</div>
</body>

Full code see in Plunk.

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

1 Comment

Yes+1. The first part is the straight answer, the second part rather irrelevant.
0

Exactly, adding to the @Roman's point, when you use '=' in declaring the directive's scope variable it should be declared the the parent controller as well, otherwise you can use '@'.

Comments

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.