假设我有控制器:
angular.module('tf').controller('Ctrl', function($scope){
$scope.params = {
orderBy: null
};});
指令“共同”:
angular.module('tf').directive("common", function() {
return {
restrict: 'E',
replace: true,
template: '<div><outer order-by="orderBy"><inner order-by-field="name1"></inner><inner order-by-field="name2"></inner></outer></div>',
controller: function ($scope) {
},
scope: {
orderBy: '='
},
link: function (scope, element, attrs) {
}
}});
Controller在其模板中使用指令:
<div ng-app="tf">
<div ng-controller="Ctrl">
<common order-by="params.orderBy"></common>
<div style="color:red">{{params.orderBy}}</div>
</div>
该指令使用指令“outer”:
angular.module('tf').directive("outer", function() {
return {
restrict: 'E',
transclude: true,
replace: true,
template: '<div ng-transclude></div>',
controller: function ($scope) {
this.order = function (by) {
$scope.orderBy = by
};
},
scope: {
orderBy: '=',
}
}});
哪个是指令“inner”的父级:
angular.module('tf').directive("inner", function() {
return {
require: '^outer',
restrict: 'E',
transclude: true,
replace: true,
template: '<div ng-click="onClicked()">{{orderByField}}</div>',
controller: function ($scope) {
$scope.onClicked = function () {
$scope.outer.order($scope.orderByField);
}
},
scope: {
orderByField: '@'
},
link: function (scope, element, attrs, outer) {
scope.outer = outer;
}
}});
指令“outer”通过它的控制器与指令“inner”共享“order”方法。指令“inner”通过使用“require”机制来访问它。
由于某种原因,这没有按预期工作(控制器的属性每次由指令更改时都不会更新)。如果我将“orderBy”放入对象(例如{“order”:{“by”:null}})并使用对象而不是字符串值,则一切都按预期工作(控制器范围由指令正确更新)。我知道“总是使用点”最佳实践原则,但我不想在这里使用它,因为它会使我的指令的API不那么直观。
这是jsfiddle: http://jsfiddle.net/A8Vgk/1254/
由于