Angular的绑定不适用于指令中添加的元素

时间:2016-10-06 07:39:28

标签: javascript angularjs

我的指示是

myApp.directive('myRequired', function ($compile, gettextCatalog) {
    return {
        link: function (scope, element, attrs) {
            var noticeContainer = '<div class="inputError" ng-show="showSomeNotices" translate>{{errorMessage}}</div>';
            element.after(noticeContainer);

        scope.$on("submitstart", function (event, data) {
            scope.showSomeNotices = false;
            if (!element.val()) {
                scope.errorMessage = gettextCatalog.getString("Empty field");                
                scope.showSomeNotices = true;

            }
        });
    }};
});

但是ng-show和bracets {{errorMessage}}忽略了连接的变量。我总是在页面上看到{{errorMessage}}作为文字。怎么解决?

1 个答案:

答案 0 :(得分:2)

在上面的评论中提到你必须像这样编译字符串:

…
var noticeContainer = '<div class="inputError" ng-show="showSomeNotices" translate>{{errorMessage}}</div>',
    content = $compile(noticeContainer)(scope);

element.after(content);
…

我为你创建了一个plunkr:https://plnkr.co/edit/9HKoLg401Thip2cLHYsb?p=preview