0

似乎存在一个错误,即从 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/

任何帮助表示赞赏。

4

1 回答 1

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/

于 2013-08-20T15:17:31.260 回答