AngularJS:如何使用可选的属性参数编写元素指令?

时间:2014-07-23 22:28:30

标签: angularjs angularjs-directive

我正在AngularJS指令中执行我的第一步。只需将此项设置为输出产品名称的练习:

.directive('productname', function (Prefs) {
        return {
            restrict: 'E',
            replace: true,
            transclude: true,
            templateUrl: '/partials/productname.html',
            link: function (scope, element, attrs) {
                scope.brand = Prefs.owner;
            }
        }
    })

productname.html

<span class="productname"><span class="brand">{{brand}}</span> <span class="product" ng-transclude>{{productname}}</span></span>

所以用法很简单:<productname>{{product.name}}</productname>

现在,有人可以告诉我如何通过添加一个标志来输出链接的产品名来使这个指令可配置吗?

用法为:<productname linked>{{product.name}}</productname>,输出/模板为:

<span class="productname"><a href="/edit/{{id}}"> <span class="brand">{{brand}}</span> <span class="product" ng-transclude>{{productname}}</span></a></span>

看起来很复杂,我无法弄清楚逻辑应该注入的位置......

1 个答案:

答案 0 :(得分:5)

首先,您应该使用指令声明的scope属性。此外,在这种情况下,您不需要transclude。像这样:

.directive('productname', function (Prefs) {
    return {
        restrict: 'E',
        scope: {
            product: "=",
            linked: "="
        },
        replace: true,
        templateUrl: '/partials/productname.html',
        link: function (scope, element, attrs) {
            // scope.product and scope.linked are automatically set
            scope.brand = Prefs.owner;
        }
    }
})

模板:

<span class="productname" ng-switch="linked">
    <a href="/edit/{{id}}" ng-switch-when="true">
        <span class="brand">{{brand}}</span>
        <span class="product">{{product.name}}</span>
    </a>
    <span ng-switch-default>
        <span class="brand">{{brand}}</span>
        <span class="product">{{product.name}}</span>
    </span>
</span>

像这样调用模板:

<productname product="product"></productname>

或:

<productname product="product" linked="'true'"></productname>

更新

如果要将linked属性用作标记,可以使用attrs变量来执行此操作:

.directive('productname', function (Prefs) {
    return {
        restrict: 'E',
        scope: {
            product: "="
        },
        replace: true,
        templateUrl: '/partials/productname.html',
        link: function (scope, element, attrs) {
            // scope.product is automatically set
            scope.linked = typeof attrs.linked != 'undefined';
            scope.brand = Prefs.owner;
        }
    }
})

这样称呼:

<productname product="product" linked></productname>