我试图在两个指令之间“共享”一个范围,如下所示:
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>
但是,无论我做什么,我都无法使icon-source检索到正确的值(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
并尝试了许多转运组合。
我做错了什么?
答案 0 :(得分: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>",
};
});
我已经组装了一个可以访问的here工作的plunker,你应该全部设置:)