在其模板中使用Angular Directive属性

时间:2013-06-27 14:01:34

标签: javascript angularjs angularjs-directive

如何在指令中使用属性的值?我的元素看起来像这样:

<div class="tooltip-icon" 
  data-my-tooltip="click" 
  data-tooltip-title="foo" 
  data-tooltip-content="test content"></div>

我想在我的指令模板中使用它,如下所示:

mainApp.directive('myTooltip',
    function() {

        // allowed event listeners
        var allowedListeners = ["click"];

        return {
            restrict: 'A',
            template:   '<div class="tooltip-title">...</div>' +
                        '<div class="tooltip-content">' +
                        '...</div>',
            link: function(scope, elm, attrs) {
                if(allowedListeners.indexOf(attrs.myTooltip) != -1){
                    elm.bind(attrs.myTooltip, function(){
                        ...
                    });
                }

            }
        };
    }
);

三点的位置应该有代码,但我无法弄清楚如何将attrs对象(attrs.tooltipTitle等)的内容放入该模板中。

2 个答案:

答案 0 :(得分:33)

您可以拉出属性并将它们放入指令的范围内,如下所示:

angular.module('myApp', []).
directive('myTooltip', function ($log) {
    // allowed event listeners
    var allowedListeners = ["click"];
    return {
        restrict: 'A',
        template:   '<div class="tooltip-title">{{tooltipTitle}}</div>' +
                    '<div class="tooltip-content">' +
                    '{{tooltipContent}}</div>',
        scope: {
            tooltipTitle: '@tooltipTitle',
            tooltipContent: '@tooltipContent'
        },
        link: function (scope, elm, attrs) {
            if (allowedListeners.indexOf(attrs.myTooltip) != -1) {
                elm.bind(attrs.myTooltip, function () {
                    $log.info('clicked');
                });
            }

        }
    };
});

这是小提琴:http://jsfiddle.net/moderndegree/f3JL3/

答案 1 :(得分:3)

这个问题已经已经得到了答案,但是我将分享我的Angular代码,因为这是一个看一些工作示例通常很有用的领域。

我有几个网页,每个网页都有自己的Angular控制器,我想要一种方法在每个页面上弹出一个“Please Wait”弹出窗口,当任何一个页面被称为HTTP GET或POST Web服务。

enter image description here

为此,我的每个网页都包含以下一行:

<please-wait message="{{LoadingMessage}}" ></please-wait>

...绑定到该页面控制器中的$scope ...

$scope.LoadingMessage = "Loading the surveys...";

以下是我的<please-wait>指令的代码:

myApp.directive('pleaseWait',  
    function ($parse) {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                message: '@message'
            },
            link: function (scope, element, attrs) {
                scope.$on('app-start-loading', function () {
                    element.fadeIn(); 
                });
                scope.$on('app-finish-loading', function(){
                    element.animate({
                        top: "+=15px",
                        opacity: "0"
                    }, 500);
                });
            },
            template: '<div class="cssPleaseWait"><span>{{ message }}</span></div>'
        }
    });

注意它如何获取message属性(在此示例中为{{LoadingMessage}})并可以在指令的模板中显示其值。

(这实际上是我答案中唯一直接回答这个问题的部分,但请继续阅读,以获得更多提示'''''

现在,很酷的部分是我的每个控制器都会在想要从Web服务加载或保存任何数据时调用Angular数据服务。

   $scope.LoadAllSurveys = function () {
        DataService.dsLoadAllSurveys($scope).then(function (response) {
            //  Success
            $scope.listOfSurveys = response.GetAllSurveysResult;
        });
   }

dsLoadAllSurveys函数看起来像这样......

myApp.webServicesURL = "http://localhost:15021/Service1.svc";

myApp.factory('DataService', ['$http', 'httpPostFactory', 'httpGetFactory',
    function ($http, httpPostFactory, httpGetFactory) {

        var dsLoadAllSurveys = function (scope)
        {
            //  Load all survey records, from our web server
            var URL = myApp.webServicesURL + "/getAllSurveys";
            return httpGetFactory(scope, URL);
        }

        return {
            dsLoadAllSurveys: dsLoadAllSurveys
        }
    }]);

而且,至关重要的是,所有“GET”网络服务调用都通过以下功能进行,该功能会为我们显示“请等待”控件...然后在服务完成后将其消失。

myApp.factory('httpGetFactory', function ($http, $q) {
    return function (scope, URL) {
        //  This Factory method calls a GET web service, and displays a modal error message if something goes wrong.
        scope.$broadcast('app-start-loading');          //  Show the "Please wait" popup

        return $http({
            url: URL,
            method: "GET",
            headers: { 'Content-Type': undefined }
        }).then(function (response) {
            scope.$broadcast('app-finish-loading');     //  Hide the "Please wait" popup
            if (typeof response.data === 'object') {
                return response.data;
            } else {
                // invalid response
                return $q.reject(response.data);
            }
        }, function (errorResponse) {
            scope.$broadcast('app-finish-loading');     //  Hide the "Please wait" popup

            //  The WCF Web Service returned an error.  
            //  Let's display the HTTP Status Code, and any statusText which it returned.
            var HTTPErrorNumber = (errorResponse.status == 500) ? "" : "HTTP status code: " + errorResponse.status + "\r\n";
            var HTTPErrorStatusText = errorResponse.statusText;

            var message = HTTPErrorNumber + HTTPErrorStatusText;

            BootstrapDialog.show({
                title: 'Error',
                message: message,
                buttons: [{
                    label: 'OK',
                    action: function (dialog) {
                        dialog.close();
                    },
                    draggable: true
                }]
            });

            return $q.reject(errorResponse.data);
        });
    };
});

我喜欢这段代码的是这个功能在显示/隐藏“请稍候”弹出窗口之后,如果发生错误,它还会看到显示错误消息(使用优秀的BootstrapDialog库),在将错误结果返回给调用者之前。

如果没有这个工厂函数,每当我的一个Angular控制器调用一个Web服务时,它就需要显示,然后隐藏“Please wait”控件,并检查错误。< / p>

现在,我可以调用我的网络服务,并留下 it 以告知用户是否出现问题,否则我可以认为这一切都有效,并处理结果。

这使我可以使用更简单的代码。记住我如何调用该Web服务:

   DataService.dsLoadAllSurveys($scope).then(function (response) {
        //  Success
        $scope.listOfSurveys = response.GetAllSurveysResult;
    });

代码看起来好像它没有进行任何错误处理,而实际上,它都是在一个地方的幕后进行的。

我仍然使用Angular获得工厂和数据服务,但我认为这是他们如何提供帮助的一个很好的例子。

希望这有意义,并且有所帮助。