【问题标题】:$compile in Directives指令中的 $compile
【发布时间】:2015-10-10 23:16:55
【问题描述】:

嘿,伙计们,我正在计划一个我正在制定的指令,它本质上是一个带有计时器的弹出窗口。基本上计划是传入一个对象,该对象可以配置属性来构造消息。该指令将包含 html 模板,我们将根据服务中设置的属性附加 message/html。例如:

$rootScope.timer = 'recursive time fn goes here'

obj = {
message : '<span ng-click="connect()">Custom message goes here {{ timer }} </span>'
}

Popup.pop(obj);

等等。问题的关键是$rootScope 计时器需要倒计时(这在控制器中很简单),但是如果插值,指令将 html 设置为字符串,如果我是正确的,则不会更新值。我的问题是我如何获得指令以在指令内呈现计时器。我需要在directive 中使用$compile 吗?如果是这样怎么办?此外,如果我需要一个 ng-click 函数,我将如何从该服务中传递一个函数?很抱歉,如果它令人困惑,请提出问题。

【问题讨论】:

  • 弹出窗口需要无处不在吗?我肯定会使用像“alertPopUpService”这样的服务来管理弹出窗口而不是指令。
  • 是的,尽管如此,但不幸的是,它确实需要无处不在。假设我们必须通过指令执行 i
  • 我实际上不认为这是一个很好的指令用例。我会尝试一个服务的例子,如果它不适合我会回到指令之一。 (如果之前没有人回答)
  • plnkr.co/edit/Fmhs6Dj8ozq1v1oTJGHG?p=preview 这是一个使用服务的小例子。你只需要在一个控制器(主控制器)中绑定警报,然后用一些 CSS 在他的身体上添加一个 ng-repeat 就可以了。

标签: javascript angularjs using-directives


【解决方案1】:

试试这个

//you can add your custom messge and time function returning value to the way u want 

// this is the basic way to do
var testing = angular.module('testing', [])

testing.directive('mydir', function ($compile, $rootScope) {
    
    var template = '<span ng-click="connect()">custom message</span>'
    return {

        restrict: 'E',

        link: function (scope, ele, attribute) {


            scope.connect = function () {

                alert('popup' +  new Date().getTime());
            }
            var content = $compile(template)(scope);

            ele.append(content)


        }

    }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
    <div ng-app="testing">


        <mydir></mydir>
    </div>

</body>

【讨论】:

    猜你喜欢
    • 2015-08-24
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    相关资源
    最近更新 更多