我有一个带有换行符和 URL 的文本:
第一行\n在 http://www.example.com 和\n 在 http://stackoverflow.com 找到我
。
我想在按下 copy
按钮后更新 ng-repeat
值。
我有这个 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>
Controller :
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
中的文本并按下 copy
按钮。我希望在 ng-repeat
中显示更改。
只有当我添加一个新行而不是行内容时它才有效。
这里有什么问题?这是我的 Fiddle
最佳答案
只需从 ng-repeat
中删除 track by $index
。这是因为你告诉 Angular note_value.split('\n')
的值只会在 $index
发生变化时发生变化,即换行分割后的数组。
但是 track by
的默认实现是每个项目的标识。因此,当您更改默认实现以通过 $index
跟踪它并且您不是不添加新行而是更新任何现有行的内容时,Angular 无法检测到一个变化。
更新
移除track by $index
函数会在拆分后有相同值时抛出异常。所以你可以使用一个简单的函数,比如:(在你的 Controller 中定义它)
$scope.indexFunction = function($index, val) {
// Creating an unique identity based on the index and the value
return $index + val;
};
然后在您的 ng-repeat
中使用它,例如:
<p ng-repeat="row in note_value.split('\n') track by indexFunction($index, row)"></p>
关于javascript - 更改文本区域模型后指令不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34265554/