Angular Js指令更新DOM上的范围值

时间:2017-05-12 11:27:33

标签: angularjs angularjs-directive

我有一个根据鼠标事件更新DOM的指令。

<input mask-directive
ui-mask="{{phoneMask}}"
placeholder="{{phonePlaceholder}}"
ui-mask-placeholder
class="form-control input-phone">

指令代码

.directive('maskDirective', function () {

    return {
        restrict: 'A',
        scope: {
            uiMask: '@',
            phonePlaceholder : '@'
        },
        link: function (scope, element) {
            element.on('mouseover', function () {
                scope.uiMask = '999-999-9999';
                scope.phonePlaceholder = '';
            });
            element.on('mouseenter', function () {
                //something
            });
            element.on('mouseleave', function () {
                //something
            });
        }
    };
});

问题是 -

element.on('mouseover', function () {
    scope.uiMask = '999-999-9999';
    scope.phonePlaceholder = '';
});

它不会更新DOM上的uiMask和phonePlaceholder值。

1 个答案:

答案 0 :(得分:0)

您应该重新构建代码并使用有角度的模板和事件。

指令

.directive('maskDirective', function () {
    return {
        restrict: 'AE',
        scope: {
            uiMask: '@',
            phonePlaceholder : '@'
        },
        templateUrl: 'myTemplate.html',
        link: function (scope, element) {
            scope.myFunc = myFunc;

            function myFunc() {
                scope.uiMask = '999-999-9999';
                scope.phonePlaceholder = '';
            }
        }
    };
});

元素

<mask-directive
ui-mask="{{phoneMask}}"
placeholder="{{phonePlaceholder}}"
ui-mask-placeholder>

模板myTemplate.html

<input ngMouseOver="myFunc()" class="form-control input-phone">