[英]Angular Directive Pass back scope variable
我试图做一个指令,基本上是一个带有最大长度计数器的文本框。 我的指令如下。 基本上是一个文本框,将告诉用户他们只剩下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;
}
}
}
});
模板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>
我使用这样的指令。
<text-Area-Counter text="WholeDeletionText" total-Characters="250"></text-Area-Counter>
我遇到的问题是指令未更新值“ WholeDeletionText”。
我的期望是,父级中的scope.WholeDeletionText将使用在指令的textarea中写入的文本进行更新。 至少我对带有'='符号的隔离范围的理解是,它们与父级共享它。 我做错了什么,还是有更好的方法呢?
发生问题的原因是您在应用程序范围内没有WholeDeletionText
变量。
要修复它,您需要:
1)创建控制器并初始化WholeDeletionText
变量
.controller("MyController", function ($scope) {
$scope.WholeDeletionText = '123';
});
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>
完整代码请参见Plunk 。
确切地说,在@Roman的要点上,当在声明指令的作用域变量时使用'='时,也应将其声明为父控制器,否则可以使用'@'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.