我正在尝试创建 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中,我有一个<input type="text" ng-model="query" datum="sugestions" dir-three>
带有ngModel的输入,这个输入需要访问和修改 ngModel 的内容,使得作用域不被隔离。
http://jsfiddle.net/joaoneto/hbABU/3/
更新
我更新了版本,修复了我犯的一些错误,被嵌入到dirTwo中的内容,不应该有“添加”功能,属于dirTree,希望它对某人有所帮助并为人们更新此条目表示歉意......见http://jsfiddle.net/hbABU/4/