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

use*_*686 3 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;
            }
        }
    })
Run Code Online (Sandbox Code Playgroud)

productname.html

<span class="productname"><span class="brand">{{brand}}</span> <span class="product" ng-transclude>{{productname}}</span></span>
Run Code Online (Sandbox Code Playgroud)

这样用法很明显: <productname>{{product.name}}</productname>

现在,有人可以告诉我如何通过添加一个标志来输出链接的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>
Run Code Online (Sandbox Code Playgroud)

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

Alp*_*Alp 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;
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

和模板:

<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>
Run Code Online (Sandbox Code Playgroud)

像这样调用模板:

<productname product="product"></productname>
Run Code Online (Sandbox Code Playgroud)

要么:

<productname product="product" linked="'true'"></productname>
Run Code Online (Sandbox Code Playgroud)

更新

如果要将该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;
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

这样称呼它:

<productname product="product" linked></productname>
Run Code Online (Sandbox Code Playgroud)