简体   繁体   English

角指令回传范围变量

[英]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. 基本上是一个文本框,将告诉用户他们只剩下x个字符。

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: 模板html是:

<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. 我遇到的问题是指令未更新值“ WholeDeletionText”。

My expectation is that the scope.WholeDeletionText in the parent would update with the text that was written in the textarea in the directive. 我的期望是,父级中的scope.WholeDeletionText将使用在指令的textarea中写入的文本进行更新。 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. 发生问题的原因是您在应用程序范围内没有WholeDeletionText变量。

To fix it you need: 要修复它,您需要:

1) create controller and initialize WholeDeletionText variable 1)创建控制器并初始化WholeDeletionText变量

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

2) add ng-controller="MyController" directive in your main html file. 2)在您的主要html文件中添加ng-controller="MyController"指令。

<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 . 完整代码请参见Plunk

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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