如何使用 AngularJS 将值动态绑定到链接

How to dynamically bound value to a link using AngularJS

本文关键字:动态绑定 链接 何使用 AngularJS      更新时间:2023-09-26
我需要

动态生成链接的问题,因为链接是在ng-repeat中设置的。我想我需要在循环中执行自定义函数ng-repeat该函数从$http获取数据并将链接推送到$scope.array。然后href绑定到$scope.array[someIndex]....我不知道的问题是否:

  • 这是唯一的方法
  • 一个好的设计
  • 如何实现它

例:

.HTML

    <div ng-repeat-start="item in items">
        <a href="{{$scope.arrayOfUrls[$index]}}">the link</a> 
           // here execute $scope.getUrl(item ) somehow
    <div class="extra-div">
    <div ng-repeat-end=""></div>

控制器:

$scope.arrayOfUrls= [];
$scope.getUrl = function(url){
    $http.get(url).then(
        function(data){
           arrayOfUrls.push(data.link);
   }
)
}

如何在ng-repeat周期内执行getUrl

我不能href直接绑定到getUrl函数,因为有$http最终导致无限摘要循环。

此外,承诺可以不按顺序返回,因此期望对getUrl的第一次调用会将链接推送到$scope.arrayOfUrls[0]是错误的假设。

更新:

正如@Claies建议的那样,我尝试预取这样的链接:Contoller 执行$scope.loadFeed();

$scope.loadFeed = function() {
    http.jsonp('feed url').then(function(res) {
            $scope.feeds = res.data.responseData.feed.entries;
            $scope.feeds.forEach(function(e) {
                    // prefetch content and links for each feed
                    //hook new entryStateUrl property to feed objects
                    e['entryStateUrl'] = $scope.getEntryStateUrl(e.link); // e['entryStateUrl'] is undefined
                    })
            })

    }
}
$scope.getEntryStateUrl = function(inputUrl) {
    $http.get(inputUrl).then(function(data) {
        // do stuff
        return data.link;
    });
}
            }

现在似乎我正在尝试预取网址,但e['entryStateUrl'] undefined......

问题可能是关于在未完成获得结果时分配范围变量$http......此外,似乎有嵌套的promises$http.jsonp,里面$http.get.

如何解决?

由于这需要 UI 增强,因此指令将是一个很好的方法。像这样的指令怎么样(JSFiddle在这里)。 请注意,我在这里调用$window.open - 您可以将其替换为应用程序所需的任何内容。:-

    todoApp.directive('todoLinks', ['$window',function ($window) {
    var directive = {};
    directive.restrict = 'A';
    directive.transclude = 'true';
    directive.scope = { ngModel: '=ngModel', jsOnClick:'&' };
    directive.template = '<li ng-repeat="item in ngModel"><a href="javascript:void(0)" ng-click="openLink($index)">{{item.name}}</a></li>';
    directive.link = function ($scope, element, attributes) {
        $scope.openLink = function (idx) {
            $window.open($scope.ngModel[idx].link); //Replace this with what your app. requires
                if (attributes.jsOnClick) {
                    //console.log('trigger post jsOnClick');
                    $scope.jsOnClick({ 'idx': idx });
                }
        };
    };
    return directive;
}]);

当控制器像这样填充待办事项时:-

todoApp.controller("ToDoCtrl", ['$scope','$timeout','dbService',function($scope, $timeout, dbService)
{
    $scope.todo=[{"name":"google","link":"http://www.google.com"},{"name":"bing","link":"http://www.bing.com"},{"name":"altavista","link":"http://www.altavista.com"}];
}]);

该指令的用法很简单:-

<div todo-links ng-model="todo"></div>