指令中的$compile

$compile in Directives

提问人:Indrick 提问时间:7/21/2015 最后编辑:ngLoverIndrick 更新时间:7/21/2015 访问量:41

问:

嘿,伙计们,我正在计划我正在制定的指令,它本质上是一个带有计时器的弹出窗口。基本上,计划是传入一个对象,该对象可以配置属性以构造消息。该指令将包含 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);

等。问题的重点是计时器需要向下滴答(这在控制器中很容易做到),但是如果插入,该指令会将 html 设置为字符串,如果我是正确的,则不会更新该值。我的问题是我如何获得指令以使计时器在指令中滴答作响。我需要在 ?如果是这样,如何?此外,如果我需要函数,我将如何从此服务传递函数?对不起,如果它令人困惑,请提出问题。$rootScope$compiledirectiveng-click

JavaScript angularjs 使用指令

评论

0赞 Okazari 7/21/2015
弹出窗口需要无处不在吗?我肯定会使用像“alertPopUpService”这样的服务,它将管理弹出窗口而不是指令。
0赞 Indrick 7/21/2015
是的,我虽然是这样,但不幸的是,它确实需要无处不在。假设我们必须通过指令来做 i
0赞 Okazari 7/21/2015
我实际上不认为这是指令的好用例。我会尝试一个服务的示例,如果它不合适,我会回到指令。(如果之前没有人回答)
0赞 Okazari 7/21/2015
plnkr.co/edit/Fmhs6Dj8ozq1v1oTJGHG?p=preview这是使用服务的一个小例子。您只需要将警报绑定到控制器(主控制器)中,然后用一些 CSS 在他的 boddy 上添加一个 ng-repeat,仅此而已。

答:

0赞 Phani Kumar Vadlamani 7/21/2015 #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>