javascript - 更改文本区域模型后指令不会触发

标签 javascript angularjs angularjs-directive

我有一个带有换行符和 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>

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

关于javascript - 更改文本区域模型后指令不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34265554/

相关文章:

javascript - Google Maps API V3 - 管理折线

javascript - 为什么代码没有应用于页面中的每个元素

javascript - 与另一个指令一起使用时,angularjs 验证器不起作用

angularjs - 从另一个 Controller 设置 Angular 指令的属性值

javascript - AngularJS - 如果表达式为 true,则禁用选择列表选项

javascript - 如何处理 "outside"单击 Dialog (Modal)?

c# - 单击按钮激活/停用 javascript

javascript - 滚动到 ng-repeat 中数组中最后添加的记录

angularjs - 如何向 "ng-disabled"添加多个条件?

javascript - 无法执行链式 promise