2

我想知道如何在 Typeahead 的自定义模板的 ng-src 属性中使用函数。这是我的html模板:

<script type="text/ng-template" id="customTemplate.html">
    <a>
        <img ng-src="getWikiImgs({{match.model}})" width="16">
        <span bind-html-unsafe="match.label | typeaheadHighlight:query"></span>
    </a>
</script>
<div class="col-xs-10 center alt-txt-light">
    <span class="dash-pg-header-txt">Index an author!</span>
    <br/>
    <hr class="hr-separator"/>
    <br/>
    <div style="height: 1000px;">
        <h4>Search Wikipedia:</h4>
        <input type="text" ng-model="asyncSelected" placeholder="ie: John Bunyan" typeahead="item for item in getWikiResults($viewValue)" typeahead-wait-ms="500" typeahead-loading="loadingWikiResults" typeahead-template-url="customTemplate.html" class="form-control" />
        <br/>
        <i ng-show="loadingWikiResults" class="fa fa-refresh" style="text-align:left; float:left;"></i>
    </div>
</div>

因此,在自定义模板脚本中,我尝试使用 ng-src 中的函数根据 Typeahead 使用的“match.model”变量从维基百科获取相应的图像。

这是控制器:

angular.module("app").controller("AuthorCreateController", function($scope, $state, 

$stateParams, $http) {

    $scope.getWikiResults = function($viewValue) {

        return $http.get('http://en.wikipedia.org/w/api.php?', {
            params: {
                srsearch: $viewValue,
                action: "query",
                list: "search",
                format: "json"
            }
        }).then(function($response){
            var items = [];
            angular.forEach($response.data.query.search, function(item){
                items.push(item.title);
            });
            return items;
        });
    };

    $scope.getWikiImgs = function(title) {

        $.getJSON("http://en.wikipedia.org/w/api.php?callback=?",
        {
            action: "query",
            titles: title,
            prop: "pageimages",
            format: "json",
            pithumbsize: "70"
        },
        function(data) {
            $.each(data.query.pages, function(i,item){
                return item.thumbnail.source;
            });
        });
    };


});
4

2 回答 2

1

问题是您的模板没有您合理预期的范围。

解决方案是(取决于模板出现的位置)$parent.在您的函数前面链接一些调用。

有关更多详细信息,请参阅此 git 问题此问题

于 2015-07-13T03:42:36.697 回答
0

您的问题实际上在于从 ng-src 调用函数。而是使用CORS [Cross-Resource-Origin-Sharing]

这是您的代码的 Plunker: http ://plnkr.co/edit/CvqhU9?p=preview

例如,在输入中键入“a”,然后检查控制台,您会发现它确实成功地调用了该函数但是等待 2 秒,然后会出现以下内容:

XMLHttpRequest cannot load http://en.wikipedia.org/w/api.php?&action=query&format=json&list=search&srsearch=a. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://run.plnkr.co' is therefore not allowed access.

简而言之,这意味着当您在 www.foo.com 域上时,您不能从 www.bar.com 请求资源,除非 www.bar.com 启用了该资源。您可以在此处查看有关此问题的一些答案:XMLHttpRequest cannot load an URL with jQuery

我希望这有帮助。

于 2014-06-17T04:15:29.127 回答