【问题标题】:How to access the attribute of angular directive in templateUrl html content如何在templateUrl html内容中访问angular指令的属性
【发布时间】:2014-12-28 04:54:08
【问题描述】:

如何访问templateUrl html内容中的angular指令属性?

angular.module('myApp')
    .directive('questionImage', function () {
        return {
            restrict : 'E',
            scope : false,
            templateUrl : 'templates/questionImage.html',
            link : function(scope, element, attrs) {
                scope.type = attrs['type'];
            }
        }
    });

模板 HTML:

<div>
    <label>Image Links</label><br>
    <button type="button" ng-click="newImageLink('{{type}}')">+</button>
    <span ng-repeat="imageLink in questionFormData.imageUrls['{{type}}'] track by $index">
        <input type="text" ng-model="questionFormData.imageUrls['{{type}}'][$index]">
        <button type="button" ng-click="removeElement(questionFormData.imageUrls['{{type}}'], $index)">-</button>
    </span>
</div>

在这个 HTML 中,我需要访问在 DOM 中使用指令时指定的“type”属性值,如下所示。

<question-image type="optionAImages"></question-image>
<question-image type="optionBImages"></question-image>  

如何在模板 html 中获取“type”属性值?

更新:在指令定义中添加了“链接”功能。我能够获得类型,但它的值始终是最后一个指令用法。 即我总是看到optionBImages 属性的type 值。 optionAImages 值不可用。

【问题讨论】:

  • 听起来你需要隔离范围
  • @underscore 我无法隔离范围,因为我需要父控制器的很多功能。另请参阅我的更新

标签: angularjs angularjs-directive


【解决方案1】:

问题来自 scope:false 语句,因为 question-image 指令的第二次调用覆盖了由相同参数的第一次调用更改的参数

您需要将scope:false 更改为scope:true

这不会创建一个孤立的范围,但它会给指令一个控制器父范围的嵌套范围。

【讨论】:

    【解决方案2】:
     return {
               restrict : 'E',
               scope : {
               type : '@'
            },
               templateUrl : 'templates/questionImage.html'
    

    这相当于

    scope.type = attrs.type; 
    

    【讨论】:

      猜你喜欢
      • 2016-10-26
      • 2023-03-25
      • 1970-01-01
      • 2015-06-05
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      相关资源
      最近更新 更多