指令改变textarea的模型后不火 [英] Directive doesn't fire after changing textarea model
问题描述
我有换行分隔符和URL的文本:
I have a text with newline separator and URLs:
第一行\\ n查找我在http://www.example.com也\\ n在http://stackoverflow.com
。
我想更新后
按钮。 复制pressing NG-重复
值
I want to update ng-repeat
values after pressing on copy
button.
我有这样的HTML:
<div ng-controller="myCntrl">
<textarea ng-model="copy_note_value"></textarea>
<button data-ng-click="copy()">copy</button>
<div>
<p ng-repeat="row in note_value.split('\n') track by $index"
wm-urlify="row"
style="display: inline-block;"
>
</p>
</div>
</div>
控制器:
app.controller('myCntrl', function ($scope) {
$scope.note_value = "first row\nFind me at http://www.example.com and also\n at http://stackoverflow.com";
$scope.copy_note_value = angular.copy($scope.note_value);
$scope.copy = function(){
$scope.note_value = angular.copy($scope.copy_note_value);
}
});
我有指令,应采取文字,返回的 urlfied 的文本:
app.directive('wmUrlify', ['$parse', function ($parse) {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attrs) {
function urlify(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function (url) {
return '<a href="' + url + '" target="_blank">' + url + '</a>';
})
}
var text = $parse(attrs.wmUrlify)(scope);
var html = urlify(text);
element[0].inneHtml(html)
}
};
}]);
下面是一个流程:用户更改的textarea
和presses文字上的复制
按钮。我希望能表现出变化 NG-重复
。
Here is a flow: User changes text in textarea
and presses on copy
button. I expect to show the change in ng-repeat
.
它的工作原理只有当我添加一个新行,而不是行的内容。
It works only if I add a new line and not line content.
什么是错在这里?这是我的小提琴
What is wrong here? This is my Fiddle
推荐答案
仅仅通过$索引中移除跟踪
从 NG-重复
。这是因为你是在告诉角的的note_value.split('\\ n')值
时,有一个变化只会改变了通过新的生产线后,分裂的数组$指数
即大小。
Just remove the track by $index
from your ng-repeat
. This is because you are telling Angular that the value of note_value.split('\n')
will only be changed when there is a change in the $index
i.e. size of the array after splitting by new line.
但是,的默认实现的轨道是每个项目的身份。所以,当你改变了默认实现由
$指数
键,当你不不添加新行,而不是只更新现有行的内容,角度不对其进行跟踪监视能够检测到有变化。
But the default implementation of track by
is the identity of each item. So when you changed the default implementation to track it by the $index
and when you are not not adding a new line instead just updating the content of any existing line, Angular is not able to detect that there is a change.
更新
由$指数拆卸跟踪
函数将抛出时,有拆分后相同的值异常。所以,你可以使用一个简单的功能,如:(在控制器中定义它)
Removing the track by $index
function will throw an exception when there are same values after split. So you can use a simple function like: (define it in your controller)
$scope.indexFunction = function($index, val) {
// Creating an unique identity based on the index and the value
return $index + val;
};
,然后用它在你的 NG-重复
这样的:
<p ng-repeat="row in note_value.split('\n') track by indexFunction($index, row)"></p>
https://docs.angularjs.org/api/ng/directive/ngRepeat
这篇关于指令改变textarea的模型后不火的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!