【问题标题】:Why my angular directive doesn't work?为什么我的角度指令不起作用?
【发布时间】:2016-10-03 12:18:49
【问题描述】:

我有一个在单击按钮时触发的指令。指令中的函数只需更改字段的属性值。所以我尝试做的是从 'popover-trigger="blur"' 更改为 'popover-trigger="none"'。

这是我的 plunkr:http://plnkr.co/edit/L81fQgi7j1dEtf1QAZJ2?p=preview

或者代码在这里:

var app = angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
app.controller('PopoverDemoCtrl', function ($scope) {
    $scope.dynamicPopover = {
        content: 'Hello, World!',
        templateUrl: 'myPopoverTemplate.html',
        title: 'Title'
    };
    $scope.label = "Please click";
    $scope.message = "ON FOCUS trigger a tooltip";

    $scope.htmlPopover = "myPopoverTemplate.html";
});

app.directive("changeTrigger", function($compile){
    return{
        restrict: 'A',
        link: function(scope, elm, attrs)
        {
            elm.bind('click', function(){
                var t = document.getElementsByClassName('f')[0].setAttribute('popover-trigger', 'none');

            $compile(t);
            console.log("Click works");
        });
    }
}

});

html

<div ng-controller="PopoverDemoCtrl">
    <br><br><br>
    <p>{{message}}</p>
    <input class="f" type="text" value="Click me!" uib-popover-template="htmlPopover" popover-trigger="focus" popover-popup-close-delay="1000" popover-placement="right" required>

    <test-directive></test-directive>

    <script type="text/ng-template" id="myPopoverTemplate.html">
        <div>
            <p>Click the button to stop triggering tooltip!</p>
            <button change-trigger><b style="color: red">Stop tooltip</b></button>
            <div class="label label-success">page</div>
        </div>
    </script>
</div>

【问题讨论】:

    标签: angularjs angularjs-directive angular-ui-bootstrap


    【解决方案1】:

    您无法通过更改uib-popup-* 参数来重新配置 angular-bootstrap Popup 元素;但是您可以将范围变量绑定到popup-enable 属性,以便能够打开/关闭弹出窗口。添加:

    <input ... uib-popover-template="htmlPopover" popover-enable="enable" ...>
    

    $scope.enable = true;
    

    这里的问题是你的按钮和输入框有不同的作用域。但是您可以通过检索字段的范围来解决此问题:

    var t = document.getElementsByClassName('f')[0];
    var scope_ = angular.element(t).scope();
    

    当然,您需要使用$scope.$apply 作用域才能正确处理双向数据绑定:

    scope_.$apply(function () {
        scope_.enable = false;
    });
    

    Working Plunkr.

    【讨论】:

    • 哇。非常感谢。看来我在错误的地方寻找解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    相关资源
    最近更新 更多