gpt4 book ai didi

javascript - 获取子指令中的范围值

转载 作者:行者123 更新时间:2023-11-28 00:55:57 25 4
gpt4 key购买 nike

我正在使用Typeahead directive from the UI Bootstrap framework 。我在另一个指令中使用这个指令。我的外部指令定义如下:

.directive('myDirective', function () {
return {
restrict:'E',
transclude: true,
scope: {
showLinks: '=?',
query: '='
},
templateUrl: '/directives/my-directive.html',
controller: function ($scope) {
if (angular.isUndefined($scope.showLinks)) {
$scope.showLinks = true;
console.log('show links? ' + $scope.showLinks);
}
}
};
});

my-directive.html 看起来像这样:

<div style="width:100%;">
<span>{{showLinks}}</span> <!-- renders just fine -->
<input type="text" autofocus autocomplete="off" class="form-control" ng-model="query"
typeahead="option as option.Name for option in getLocation($viewValue)"
typeahead-min-length="3" typeahead-template-url="location.html" />
<script type="text/ng-template" id="location.html">
{{showLinks}} <!-- Never renders -->
<span bind-html-unsafe="match.label | typeaheadHighlight:query"></span>
</script>
</div>

我这样调用我的指令:

<my-directive show-links="true" />

我需要在用于预输入的模板内使用 showLinks 的值。但由于某种原因,它没有被传递到模板中。我相信这与范围界定有关。我通过将值绑定(bind)到 UI 中得出了这个结论,如上所示。 showLinks 的值在我的模板中显示得很好。但是,它没有出现在我的指令的 typeahead 实例的模板中。

我做错了什么?我感觉我是如此接近。然而,我已经为此工作了一整天。

感谢您提供的任何帮助!

最佳答案

typehead 指令正在创建自己的隔离范围,因此您无法访问不属于该范围的任何属性。基本上您只能访问这些属性:

scope:{
index:'=',
match:'=',
query:'='
}

但是您可以访问 mach match.model 的 model 属性,因此在您的示例中,您可以将 showLinks 变量添加为 getLocation 方法的参数,并将其值映射到选项对象:

<input type="text" autofocus autocomplete="off" class="form-control" ng-model="query"
typeahead="option as option.Name for option in getLocation($viewValue, showLinks)"
typeahead-min-length="3" typeahead-template-url="location.html" />

模板

 <script type="text/ng-template" id="location.html">
{{match.model.showLinks}} <!-- the show linLinks property is mapped inside getLocation method -->
<span bind-html-unsafe="match.label | typeaheadHighlight:query"></span>
</script>

获取位置示例:

$scope.getLocation = function(viewValue, showLinks)
{
var locations = [];
// code to fill locations

// extend each location (option) object with showLinks data
for (int i=0; i<locations.length; i++)
{
var location = locations[i];
location.showLinks = showLinks;
}

return locations;

}

关于javascript - 获取子指令中的范围值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26222511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com