将属性值传递给指令模板

时间:2015-04-29 02:26:05

标签: javascript angularjs angularjs-directive

结束目标

我们希望有一个属性可以添加到我们将与上下文帮助对话框关联的任何元素,这样当我们将鼠标光标悬停在元素上时,弹出窗口将显示帮助信息。以下是我们想要做的一个例子:

<label help-info="This is what will be displayed in the help dialog">Help Example</label>

我在将字符串参数正确传递给模板时遇到了一些麻烦。

以下是我尝试的内容:

的index.html

<html ng-app="myApp">
  <head>
    <script data-require="angular.js@*" data-semver="2.0.0-alpha.20" src="https://code.angularjs.org/2.0.0-alpha.20/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="HelpInfoDirective.js"></script>
  </head>

  <body ng-controller="myCtrl">
    <div help-info="test"></div>
  </body>
</html>

HelpInfoTemplate.html

<div>
  {{'this is a' + _attrs.help-info}}
</div>

HelpInfoDirective.js

(function(){
  var app = angular.module('myApp', []);

  app.directive('helpInfo', function(){
    return{
      restrict: 'A',
      scope: true,
      templateUrl: function(_elements, _attrs){
        'HelpInfoTemplate.html'
      }
    //  link: function(_scope, _elements, _attrs){
     //   _scope.helpAttr = _attrs.help-info;
     // }
    }  
  });
})();

首先,我尝试使用link参数传递参数,但它没有工作,所以我尝试将模板放入一个没有运气的函数中。

将属性的值传递给模板的正确方法是什么?

此外,一旦我们获得了值,我们如何修改返回的模板,以便我们可以使用ng-show来显示弹出窗口(我们最终会将其放入模态中)。我愿意接受建议。

链接到Plunk

2 个答案:

答案 0 :(得分:1)

您需要像这样分配:

  app.directive('helpInfo', function(){
    return{
      restrict: 'A',
      scope: true,
      template: '<div>{{helpAttr}}</div>',
      link: function(_scope, _elements, _attrs){
       _scope.helpAttr = _attrs.helpInfo;
     }
    }  
  });

Demo

您可以使用自己的模板并在任何需要的地方插入{{helpAttr}}绑定。

答案 1 :(得分:1)

将属性值传递给模板的正确方法是什么?

将值绑定到模板

通过编译过程将值绑定到模板。您可以使用app.directive('helpInfo', function($compile){ return{ restrict: 'A', scope: {title : '@'}, link: function(scope, el){ var newElement = $compile('<div>{{title}}</div>')(scope); el.hover(function(){ el.after(newElement); }); el.mouseout(function(){ el.nextAll().first().remove(); }); } } }); 服务在指令的link函数中编译代码,并提供模板需要绑定的范围:

<div help-info title="I am a title">Click me</div>

定义指令的范围

您需要为指令设置一个独立的范围,并指定属性的名称,您将在其中定义弹出窗口中显示的文本。我在这个例子中使用'title'作为属性。

然后你可以使用这样的指令:

"""
Tool to get the origin of ResourceWarning warnings on files and sockets.

Run python with -Wd to display warnings and call enable().

Use the new tracemalloc added in Python 3.4 beta 1.

Limitation: it does not work for text files, only for binary files. See:
http://bugs.python.org/issue19829

--

FileIO constructor calls ResourceWarning with the text representation of the
file, so ResourceWarning constructor does not have access to the file object.

Replacing ResourceWarning class in __builtins__ does not work because io.FileIO
destructor has an hardcoded reference to ResourceWarning.

Replacing io.FileIO doesn't work neither because io.open has an hardcoded
reference to io.FileIO.

Replacing warnings.showwarning to inspect the frame of the caller does not
work because the FileIO destructor is called when the last reference to the
file is set to None. So there is no more reference to the file.
"""
from io import FileIO as _FileIO
from socket import socket as _socket
import _pyio
import builtins
import linecache
import socket
import sys
import traceback
import tracemalloc
import warnings

def warn_unclosed(obj, delta=1):
    delta += 1
    tb = tracemalloc.get_object_traceback(obj)
    if tb is None:
        return
    try:
        warnings.warn("unclosed %r" % obj, ResourceWarning, delta + 1)
        print("Allocation traceback (most recent first):")
        for frame in tb:
            print("  File %r, line %s" % (frame.filename, frame.lineno))
            line = linecache.getline(frame.filename, frame.lineno)
            line = line.strip()
            if line:
                print("    %s" % line)

        if 0:
            frame = sys._getframe(delta)
            tb = traceback.format_stack(frame)
            print("Destroy traceback (most recent last):")
            for line in tb:
                sys.stdout.write(line)
            sys.stdout.flush()
    finally:
        obj.close()

class MyFileIO(_FileIO):
    if 0:
        def __init__(self, *args, **kw):
            _FileIO.__init__(self, *args, **kw)
            tb = tracemalloc.get_object_traceback(self)
            if tb is None:
                raise RuntimeError("tracemalloc is disabled")

    def __del__(self):
        if not self.closed:
            warn_unclosed(self)
        if hasattr(_FileIO, '__del__'):
            _FileIO.__del__(self)

class MySocket(_socket):
    if 0:
        def __init__(self, *args, **kw):
            _socket.__init__(self, *args, **kw)
            tb = tracemalloc.get_object_traceback(self)
            if tb is None:
                raise RuntimeError("tracemalloc is disabled")

    def __del__(self):
        if not self._closed:
            warn_unclosed(self)
        if hasattr(_socket, '__del__'):
            _socket.__del__(self)

def patch_open():
    # Already patched
    if _pyio.FileIO is MyFileIO:
        return

    # _io.open() uses an hardcoded reference to _io.FileIO
    # use _pyio.open() which lookup for FilIO in _pyio namespace
    _pyio.FileIO = MyFileIO
    builtins.open = _pyio.open

def patch_socket():
    socket.socket = MySocket

def enable(nframe=25):
    if not tracemalloc.is_tracing():
        tracemalloc.start(nframe)
    patch_open()
    patch_socket()

def main():
    tracemalloc.start(25)

    print("=== test unbuferred file ===")
    patch_open()
    f = open(__file__, "rb", 0)
    f = None
    print()

    print("=== test socket ===")
    patch_socket()
    s = socket.socket()
    s = None
    print()

if __name__ == "__main__":
    main()

演示

这是一个显示此动作的Plunker。

http://plnkr.co/edit/VwdHC3l9b3qJ4PF6cGV1?p=preview

此外,一旦我们获得了该值,我们如何修改返回的模板,以便我们可以使用ng-show来显示弹出窗口

在我提供的示例中,我使用jQuery hover()和mouseout()事件来响应悬停在DOM元素上和远离DOM元素的用户。如果你想更进一步,这里的a tutorial显示了如何将弹出窗口或警报放入服务中。