1

次のように、2 つのディレクティブ間でスコープを「共有」しようとしています。

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 ディレクティブのスコープを削除し、解析された属性の変更を監視することだと思います。

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>",
  };
});

ここでアクセス可能な作業プランカーを組み立てました。これですべての設定が完了したはずです:)

于 2013-10-08T17:30:30.970 に答える