基本上我正在创建一个字符计数器,它有2个输入字段来填写模板。问题是其中一个字段是可选的,并且具有样板文本,如果选中,则会添加到字符计数中。所以我最大的困难就是在两个输入区域中获得字符串的长度。模型更改时,render方法未运行。我很困惑为什么会这样。
var $scope;
var app = angular.module('miniapp', []);
function Ctrl($scope) {
$scope.form = {}
}
app.directive('charcount', function(){
return {
restrict: 'E',
require: 'ngModel',
link: function (scope, el, attrs, controller){
controller.$render = function(){
var data = controller.$modelValue
var codeLen = 0, descLen = 0;
if (data.code){
codeLen = data.code.length
}
if (data.desc){
descLen = data.desc.length
}
console.log(descLen, codeLen);
}
}
}
})
答案 0 :(得分:1)
我从未使用 $ render ,但我使用ng-change来调用 textInput 上的函数并创建 countChange 函数来计算长度文本。
HTML中的示例
<div ng-app="miniapp">
<div ng-controller="Ctrl">
<form>
<label for="desc">Description</label>
<textarea ng-change="countChange()" id="desc" ng-model="form.desc"></textarea>
<charcount ng-model="form">
<label for="code">Code</label>
<input id="code" ng-change="countChange()" ng-model="form.code"/>
</form>
<p id="preview">Some filler text here user input {{form.desc}}
<span ng- show="form.code">
Some optional text here plus code {{form.code}}
</span>
</p>
</div>
</div>
指令中的
var app = angular.module('miniapp', []);
function Ctrl($scope) {
}
app.directive('charcount', function(){
return {
restrict: 'E',
require: 'ngModel',
controller: function($scope) {
$scope.countChange= function() {
var codeLen = 0;
var descLen = 0;
if($scope.form.desc){
descLen = $scope.form.desc.length;
}
if($scope.form.code){
codeLen = $scope.form.code.length;
}
console.log(codeLen,descLen);
}
},
link: function (scope, el, attrs, controller){
}
}})