问题: 如果用户在首先加载的字段中写入内容(第一个指令),则调用的ng-repeat位于第二个指令中。
<div style="padding: 20px;">
<p>First directive :</p>
<span search-box ng-model="toto"></span>
<hr>
<p>Second directive :</p>
<span search-box ng-model="titi"></span>
</div>
myApp.directive('searchBox', [function() {
return {
restrict: 'A',
scope: {
model: '=ngModel',
},
template: ''
+'<div>'
+ '<input type="text" ng-model="model" />'
+ '<ul style="background-color:#e1e1e1; width: 142px; padding: 15px;" ng-show="cities.length">'
+' <li ng-repeat="city in cities">'
+' {{city.label}}'
+' </li>'
+ '</ul>'
+'</div>',
replace: true,
transclude: true,
link: function(scope, element, attrs, ngModel) {
scope.cities = [];
scope.$watch('model', function (newValue, oldValue) { if(newValue != oldValue && newValue.length > 0) search(newValue) });
search = function(input) {
scope.cities = [
{label: 'Paris'},
{label: 'London'},
{label: 'New York'},
{label: 'Berlin'},
{label: 'Lisbonne'}
];
};
}
}
请在第一个字段中写一些内容,结果框显示在第二个字段下。为什么ul不引用自己的指令?
答案 0 :(得分:1)
这是因为您在指令的隔离范围之外定义了搜索功能。要使代码工作,您需要在范围内定义函数:
scope.$watch('model', function (newValue, oldValue) { if(newValue != oldValue && newValue.length > 0) scope.search(newValue) });
scope.search = function(input) {
scope.cities = [
{label: 'Paris'},
{label: 'London'},
{label: 'New York'},
{label: 'Berlin'},
{label: 'Lisbonne'}
];
};
虽然您在函数中未使用隔离范围,但它使用调用者可用的最后一个范围(您的函数定义在您的示例中被调用两次),因此函数被重新定义两次,第二个定义使用隔离范围从第二个实例调用两个调用中都使用了指令。
答案 1 :(得分:1)
在$ watch之前移动搜索功能的声明。
scope.cities = [];
var search = function(input) {
scope.cities = [
{label: 'Paris'},
{label: 'London'},
{label: 'New York'},
{label: 'Berlin'},
{label: 'Lisbonne'}
];
};
scope.$watch('model', function (newValue, oldValue) { if(newValue != oldValue && newValue.length > 0) search(newValue)});