我正在尝试创建3个指令:
.directive('dirOne', function () {
return {
restrict: 'E',
transclude: true,
replace: true,
controller: function ($scope, $element, $attrs) {
this.add = function (tag) {
tag && $scope.tags.push(tag);
};
},
template: '<div><p>Bucket from directive: {{tags}}</p><div ng-transclude></div></div>'
};
})
.directive('dirTwo', function () {
return {
restrict: 'A',
replace: true,
require: '^dirOne',
link: function (scope, element, attrs, dirOne) {
scope.add = function (tag) {
dirOne.add(tag);
};
},
template: '<div>'+
' <input type="text" ng-model="query" datum="sugestions" dir-three>' +
' <button ng-click="add(query)">add</button>' +
'</div>'
};
})
.directive('dirThree', ['$compile', function ($compile) {
var itemsTemplate = '<span class="sugestions"><span ng-repeat="item in datum|filter:query">{{item.name||item}}</span></span>';
return {
restrict: 'A',
transclude: true,
replace: true,
require: 'ngModel',
scope: {
datum: '=',
query: '=ngModel'
},
link: function (scope, element, attrs) {
var parent;
element.wrap('<span>');
parent = element.parent();
parent.append(angular.element($compile(itemsTemplate)(scope)));
}
};
}])
在 dirTwo 和 dirThree 中,我有 ngModel 的输入<input type="text" ng-model="query" datum="sugestions" dir-three>
,此输入需要访问和修改ngModel的内容,因此范围不是孤立的。
http://jsfiddle.net/joaoneto/hbABU/3/
我更新了版本,修复了我提交的一些错误,dirTwo中被转换的内容,不应该有&#34; ADD&#34;功能,属于dirTree,希望它可以帮助某人并为peopl更新此条目道歉......请参阅http://jsfiddle.net/hbABU/4/