AngularJS:来自http调用的模型数据在指令中不可用

时间:2013-08-20 14:51:53

标签: angularjs angularjs-directive angularjs-scope

似乎存在一个错误,即从http调用中获取的模型数据存在于$ scope中,但不存在于指令中。以下是说明问题的代码:

Jsfiddle:http://jsfiddle.net/supercobra/hrgpc/

var myApp = angular.module('myApp', []).directive('prettyTag', function($interpolate) {
return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      var text = element.text();
        //var text = attrs.ngModel;   
        var e = $interpolate(text)(scope);
        var htmlText = "<b>" + e + "</b>";
        element.html(htmlText);
    }
};
});

function MyCtrl($scope, $http, $templateCache) {
$scope.method = 'JSONP';
$scope.url = 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero';

$scope.fetch = function () {
    $scope.code = null;
    $scope.response = null;

    $http({
        method: $scope.method,
        url: $scope.url,
        cache: $templateCache
    }).
    success(function (data, status) {
        $scope.status = status;
        $scope.data = data;
    }).
    error(function (data, status) {
        $scope.data = data || "Request failed";
        $scope.status = status;
    });
};

}

HTML

<div ng-controller="MyCtrl">
<h1>Angular $http call / directive bug</h1>
<p>This fiddle illustrates a bug that shows that model w/ data fetched via an http call
is not present within a directive.</p>
<hr>
<h2>HTTP call settings</h2>
<li>Method: {{method}}
    <li>URL: {{url}}
        <br>
        <button ng-click="fetch()">fetch</button>
        <hr/>
         <h3>HTTP call result</h3>

        <li>HTTP response status: {{status}}</li>
        <li>HTTP response data: {{data}}</li>
            <hr/>
            <h2>Pretty tag</h2>
            <pretty-tag>make this pretty</pretty-tag>

            <hr/>
            <h3 style="color: red" >Should show http response data within pretty tag</h3>
            [<pretty-tag>{{data}}</pretty-tag>] // <=== this is empty

</div>

Jsfiddle:http://jsfiddle.net/supercobra/hrgpc/

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:1)

您正在替换指令实现中的指令内容。由于$ http请求是异步的,因此该指令在检索数据并分配给范围之前完成。

在指令内观察data变量,然后重新渲染内容,例如

 scope.$watch(attrs.source,function(value) {
                var e = $interpolate(text)(scope);
                var htmlText = "<b>" + e + "</b>";
                element.html(htmlText);
            });

根据@Marks反馈和您的要求,我有更新小提琴 http://jsfiddle.net/cmyworld/V6sDs/1/