指令没有't更改文本区域模型后发生火灾

Directive doesn't fire after changing textarea model

本文关键字:模型 区域 文本 火灾 指令      更新时间:2023-09-26

我有一个带有换行符和URL的文本:

CCD_ 1。

我想在按下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>

控制器:

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);   
    }
});

我有一个指令,应该接受文本并返回URL化文本:

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,只有当first row'nFind me at http://www.example.com and also'n at http://stackoverflow.com0发生变化时,note_value.split(''n')的值才会发生变化,即通过新行分割后的阵列大小。

但是track by的默认实现是每个项目的标识。因此,当您更改默认实现以通过$index跟踪它时,并且当您不添加新行而只是更新任何现有行的内容时,Angular无法检测到有更改。

更新

当拆分后有相同的值时,删除track by $index函数将引发异常。所以你可以使用一个简单的函数,比如:(在你的控制器中定义它)

$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>

https://docs.angularjs.org/api/ng/directive/ngRepeat