指令何时用模板替换元素?

时间:2013-03-09 16:59:28

标签: javascript angularjs angularjs-directive

我正在尝试编写一个AngularJS指令,在其中我用我指定的HTML标记替换该元素,然后附加一个按钮处理程序,该处理程序在指令的控制器上调用一个函数。不幸的是,这对我不起作用。首先,这是我正在使用的代码:

    .directive('amsNewEntry', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                url: '@navigateTo'
            },
            compile: function (tElement, tAttrs) {
                var text = tAttrs.text;
                var html = '<div>'
                         + '    <a href="#" data-ng-click="showInput">' + text + '</a>'
                         + '    <input data-ng-show="isInputFieldVisible" type="text" data-ng-model="inputValue" />'
                         + '</div>';
                tElement.replaceWith(html);
                return {
                    post: function (scope, element, attrs) {
                        console.log(element);
                        console.log(scope);
                        var input = $(element).find('input');
                        if (input.length > 0) {
                            console.log('attaching handler');
                            input.keypress(function (e) {
                                alert('keypress');
                                var code = e.which || e.keyCode;
                                if (code === 13) {
                                    alert('clicked enter');
                                    scope.navigate();
                                }
                            });
                        }
                    }
                }
            },
            controller: function ($scope, $location) {
                $scope.isInputFieldVisible = false;
                $scope.url = null;
                $scope.showInput = function () {
                    $scope.isInputFieldVisible = true;
                }
                $scope.inputValue = '';
                $scope.navigate = function () {
                    var target = $scope.url + '/' + $scope.inputValue;
                    console.log(target);
                    $location.path(target);
                }
            }

问题是,在compile函数返回的post-linking函数中,当我调出element变量时,它仍然没有被编译为我指定的HTML。 tElement.replaceWith(html)行不应该这样做吗?

最后一点,input字段在屏幕上呈现,虽然我正在使用ng-show指令并将其绑定到初始化为false的isInputFieldVisible属性。任何想法为什么这不起作用?

0 个答案:

没有答案