简体   繁体   中英

Angular Directive Pass back scope variable

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?

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 .

确切地说,在@Roman的要点上,当在声明指令的作用域变量时使用'='时,也应将其声明为父控制器,否则可以使用'@'。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM