- 我在同一视图中使用了两次指令。
- 在每个指令中,我调用一个带有字段和 ul 列表的模板。
- 当用户编写某些内容时,我调用 API,它返回我一个结果数组。
- 此数组用于通过 ng-repeat(ul) 显示列表。
问题 :如果用户在首先加载的字段(第一个指令)中写入某些内容,则调用的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'}
];
};
}
}
http://jsfiddle.net/hNTrv/10/
请在第一个字段中写一些东西,结果框显示在第二个字段下。为什么UL不参考自己的指令?
发生这种情况是因为您在指令的隔离范围之外定义了搜索函数。为了使您的代码正常工作,您需要在作用域中定义函数,如下所示:
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'}
];
};
虽然您未能在函数中使用独立作用域,但它使用调用者可用的最后一个作用域(对于您的示例,您的函数定义被调用两次),因此函数被重新定义两次,第二个定义被调用,在两次调用中使用指令的第二个实例中的隔离作用域。
在$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)});
JSFiddle