【问题标题】:AngularJS: model data from http call not available in directiveAngularJS:来自http调用的模型数据在指令中不可用
【发布时间】:2013-08-20 14:51:52
【问题描述】:

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

任何帮助表示赞赏。

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案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/

    【讨论】:

    • 所以至少可以。谢谢。这也使指令锁定以观察 $scope.data 变量。有什么办法不这样做?
    • @supercobra, &lt;pretty-tag attr1="data"&gt;{{data}}&lt;/pretty-tag&gt;,然后注意该属性:scope.$watch(attrs.attr1, function(value) { ... })
    • 这告诉我所有指令都应该有一个内置的监视机制,因为它们的数据可能来自 http 调用...
    • 只要你保留对数据对象的引用,并清除并填充它而不是替换引用,这个手表就可以工作。
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 2016-06-24
    • 1970-01-01
    • 2015-02-27
    • 2019-11-15
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多