通过AngularJS指令更改占位符?

时间:2016-06-23 15:04:08

标签: angularjs angularjs-directive

我有一个文本输入字段,其占位符我想每隔几秒更改一次。但是我不想用这个污染我的控制器所以我想把这个功能封装到一个指令中。

这是我的指示:

myApp.directive('searchBox', ['$interval', function($interval) {
    return {
        restrict: 'A',
        link(scope, element, attrs) {
            $interval(function() {
                attrs.placeholder = 'New';
            }, 1000);
        }
    }
}])

和html:

<input type="text" class="form-control" placeholder="Old" ng-model="search" search-box>

然而,占位符固执地不会改变,即使在控制台attrs.placeholder中可以看到从'Hello'更改为'Test'。有什么想法吗?

PLUNKR: https://plnkr.co/edit/Oy1M8FPTXxzB9oYMJqlx?p=preview

1 个答案:

答案 0 :(得分:2)

您无法通过attr对象更改属性值(它只是元素属性的静态反映)。相反,请使用element.attr('placeholder', 'Test')attrs.$set('placeholder', 'Test')更新您的元素。