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

标签 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;
            }
        }
    })

产品名称.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>

看起来很复杂,我不太清楚应该在哪里注入(inject)逻辑......

最佳答案

首先,您应该使用指令声明的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>

关于AngularJS:如何编写带有可选属性参数的元素指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24922115/

相关文章:

angularjs - 解析指令 templateUrl 中的语法错误 ng-click

Angular 2 RC 6 Material 2 Alpha 8 不工作

javascript - AngularJS - 单击按钮时切换对象值 bool 值

angularjs - 在 ionic 应用程序中检测平板电脑

javascript - 使用 AngularJS 在输入类型编号中强制舍入步长

angularjs - 保存后项目消失

angularjs - Angular 简单指令不起作用

javascript - $window.location.href 不工作

testing - Angular http 测试

javascript - angularjs如何动态更改模板url