我有指令foo
,我想在另一个指令dropdown
上使用。问题是dropdown
指令在模板中使用了另一个名为kendo-drop-down-list
的指令。
我希望能够写
<dropdown foo>
结果应该是
<select data-kendo-drop-down-list options='dropdownOptions' data-ng-model='selected' foo="bar"></select>
问题是foo
是可选的,这意味着该指令将同时用作<dropdown>
和<dropdown foo="bar">
。
如何传输属性?或者我做错了,因为我最终遇到了这个问题?
指令
app.directive('dropdown', function() {
return {
restrict: "AE",
scope: {
selected: "=ngModel",
},
template: "<select data-kendo-drop-down-list data-k-options='dropdownOptions' data-ng-model='selected'></select>",
controller: [
'$scope', function($scope) {
$scope.dropdownOptions = {
dataSource: {
type: "odata-v4",
transport: {
read: {
url: "odata/Products",
dataType: "json",
}
},
serverFiltering: true,
}
};
}
]
};
);
答案 0 :(得分:0)
管理解决问题。灵感来自https://stackoverflow.com/a/27261632/1220627
app.directive('dropdown', function() {
return {
restrict: "AE",
scope: {
selected: "=ngModel",
},
template: function(element, attrs) {
var templateHtml = "<select data-kendo-drop-down-list data-k-options='dropdownOptions' data-ng-model='selected'></select>";
var templateElement = angular.element(templateHtml);
_.pairs(attrs.$attr).forEach(function (pair) {
var attributeName = pair[0];
var attributeNameActual = pair[1];
// ignore attribute(s) from scope
if (attributeName === "ngModel")
return;
var attributeValue = attrs[attributeName];
templateElement.attr(attributeNameActual, attributeValue);
});
return templateElement;
},
controller: [
'$scope', function($scope) {
$scope.dropdownOptions = {
dataSource: {
type: "odata-v4",
transport: {
read: {
url: "odata/Products",
dataType: "json",
}
},
serverFiltering: true,
}
};
}
]
};
);
答案 1 :(得分:0)
您可以将控制器的$scope
变量从directiveA
传递到directiveB
,如下所示:
var myApp = angular.module('myApp', []);
myApp.directive('directiveA', function() {
return {
restrict: 'E',
template: '<directive-b foo="data"></directive-b>',
scope: {
data: '='
}
}
});
myApp.directive('directiveB', function() {
return {
restrict: 'E',
template: '{{data}} I am Directive B!',
scope: {
data: '=foo'
}
}
});
myApp.controller('MyCtrl', function($scope) {
$scope.foo = 'Hi there!';
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<directive-a data="foo"></directive-a>
</div>
&#13;