簡體   English   中英

angularjs指令和自定義方法/ html

[英]Directive at angularjs and custom method/html

我有以下代碼:

<body ng-controller="testController">
    <div test-directive transform="transform()">
    </div>


    <script type="text/ng-template" id="testDirective.html">
        <div>
            <p>
                {{transform()}}
            </p>
        </div>
    </script>

    <script>
        angular.module("Test", [])
        .directive("testDirective", function() {
            return {
                templateUrl: "testDirective.html",
                scope: {
                    transform: "&"
                },
                link: function(scope) {

                }
            };
        })
        .controller("testController", function($scope) {
            $scope.transform = function() {
                return "<a ng-click='somethingInController()'>Do Something</a>";
            };

            $scope.somethingInController = function() {
                alert("Good!");
            };
        });
    </script>

</body>

因此,基本上,我要完成的工作是使用將要從控制器調用的方法創建指令。 並且該方法將對傳遞的值做些事情(在此示例中,它什么也沒有收到,但在實際代碼中卻收到)。

到那時為止,一切正常。 但是,我接下來要做的是創建一個將在控制器中調用方法的元素。 該指令既不知道哪種元素(可以是任何元素)也不知道哪種方法。 有什么辦法嗎?

小提琴示例:

http://jsfiddle.net/abrahamsustaita/C57Ft/0/-版本0

http://jsfiddle.net/abrahamsustaita/C57Ft/1/-版本1

樣例工作

http://jsfiddle.net/abrahamsustaita/C57Ft/2/-版本2

版本2現在可以使用了(我不確定這是否可行,但是可以使用...)。 但是,我無法在父控制器中執行該方法。

是。 但是,您的代碼存在一些問題。 我將首先回答您的問題。

<test-directive transform='mycustommethod'></test-directive>

// transform in the directive scope will point to mycustommethod
angular.module('app').directive('testDirective', function() {
    return {
        restrict: 'E',
        scope: {
            transform: '&'
        }
    }
});

問題是打印html將被轉義,並且您將&lt; 而不是<(等)。 您可以改用ng-bind-html,但返回的html不會被綁定。 您將需要在鏈接方法中手動注入html(您可以使用jquery),並使用var compiled = $compile(html)(scope)綁定結果。 然后調用ele.after(compiled)ele.replace(compiled)將其添加到您的頁面。

我終於得到它的工作。

解決方案被合並。 首先,我需要添加另一個指令來解析所需的元素:

.directive("tableAppendElement", function ($compile) {
    return {
        restrict: "E",
        replace: true,
        link: function(scope, element, attrs) {
            var el = angular.element("<span />");
            el.append(attrs.element);
            $compile(el)(scope);
            element.append(el);
        }
    }
})

這將接收將添加的元素/文本,然后將其注冊到范圍。

但是,問題仍然存在。 如何訪問控制器的范圍? 由於我的指令將由許多控制器使用,並且將取決於控制器的模型,因此我只設置了作用域:false。 這樣,控制器中的每個方法現在都可以從指令:D訪問

看到小提琴在這里工作 這也對我有所幫助,因為現在不需要傳遞transform方法,因此控制器也可以作為處理該方法的人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM