1

我正在尝试在两个指令之间“共享”一个范围,如下所示:

toolbarActions.directive('toolbarActions', function (toolbar) {
    return {
        restrict: 'E',
        scope: true,
        replace: true,
        link: function (scope, element, attrs) {
            scope.toolbarActions = toolbar.getActions();
        },
        template: "<div class='centered-div-container'>" +
                         "<toolbar-action ng-repeat='toolbarAction in toolbarActions' icon-source='{{toolbarAction.icon}}'></toolbar-action>>"+
                   "</div>",
    };
});

内部指令如下所示:

toolbarActions.directive('toolbarAction', function () {
    return {
        restrict: 'E',
        scope: {
           iconSource: '&'
        },
        replace: true,
        link: function (scope, element, attrs) {
            scope.imageUrl = attrs.iconSource;
        },
        template: "<div class='centered-div-content header-control' ng-click='actionFunction()'>" +
                         "<img ng-src='{{imageUrl}}' /> "+
                   "</div>",
    };
});

在以下简单的 HTML 中:

<div class="header-content">
   <toolbar-actions></toolbar-actions>
</div>

但是,无论我做什么,我都无法让图标源检索正确的值(toolbarAction.icon),而是抛出异常:

Error: [$parse:syntax] Syntax Error: Token 'toolbarAction.icon' is unexpected, expecting [:] at column 3 of the expression [{{toolbarAction.icon}}] starting at [toolbarAction.icon}}]. http://errors.angularjs.org/1.2.0-rc.2/$parse/syntax?p0=toolbarAction.icon&p1=is%20unexpected%2C%20expecting%20%5B%3A%5D&p2=3&p3=%7B%7BtoolbarAction.icon%7D%7D&p4=toolbarAction.icon%7D%7D minErr/<@http://localhost:9000/bower_components/angular/angular.js:78

我已经尝试了许多版本来替换 toolbarAction 指令上的范围定义(例如:)

scope:true
    or
scope:false

并尝试了许多跨界组合。

我究竟做错了什么?

4

1 回答 1

2

我认为在你的情况下最好的解决方案是使用 $parse 服务,删除你的 toolbarAction 指令的范围,并注意对 parsed 属性的任何修改。

在 toolbarActions 指令中,仅将 {{toolbarAction.icon}} 替换为 toolbarAction.icon :

template: "<div class='centered-div-container'>" +
            "<toolbar-action ng-repeat='toolbarAction in toolbarActions' icon-source='toolbarAction.icon'></toolbar-action>"+
          "</div>"

并且您的 toolbarAction 指令变为:

.directive('toolbarAction', function ($parse, toolbar) {
  return {
    restrict: 'E',
    replace: true,
    link: function (scope, element, attrs) {
      var getImgURL = $parse(attrs.iconSource); //get the raw json path and create a function out of it
      //Get notified when the value is reversed
      scope.$watch(getImgURL, function(value) {
        //Finally store the real value to be used in your directive template
        scope.imageUrl = value;
      });
    },
    template: "<div class='centered-div-content header-control' ng-click='actionFunction()'>" +
                 "<img ng-src='{{imageUrl}}' /> "+
               "</div>",
  };
});

我已经组装了一个可以在这里访问的工作 plunker ,你应该已经准备好了:)

于 2013-10-08T17:30:30.970 回答