angularjs - 休息调用后,Angular JS 指令未更新

标签 angularjs

从休息服务检索数据后,我遇到了 angularjs 问题。

我目前正在使用这个SO问题enter link description here中的代码显示我的数据。

myApp.directive('myTable', function () {
return {
    restrict: 'E',
    link: function (scope, element, attrs) {
        var html = '<table>';
        angular.forEach(scope[attrs.rows], function (row, index) {
            html += '<tr><td>' + row.name + '</td></tr>';
            if ('subrows' in row) {
                angular.forEach(row.subrows, function (subrow, index) {
                    html += '<tr><td>' + subrow.name + '</td></tr>';
                });
            }
        });
        html += '</table>';
        element.replaceWith(html)
    }
}
});

为了从我的休息服务获取数据,我使用以下代码:

app.factory("Entry", function($resource) {
        return $resource("/path/to/api:id");
    }); 

    app.controller("PostIndexCtrl", ['$scope', 'Entry', function($scope, Entry) {
        $scope.entries =[];
        Entry.query(function(data) {
    $scope.entries = data;
        });
    }]); 

我可以检索代码数据,但由于某种原因,我的 html 中的数据在收到数据后没有更新。就好像双向数据绑定(bind)被破坏了。

顺便说一下,如果我在列表上使用 ng-repeat,它就可以工作。

这是我的 html 上的内容:

<my-table rows='entries'></my-table>

最佳答案

您的代码存在一些问题。第一个是在指令中声明 rows 属性的方式。目前它只是一个字符串值。以下是修复代码的方法:

<my-table ng-if="entries.length>0" rows="entries"></my-table>

在这里,我们使用 ng-if 推迟指令的执行,直到 AJAX 调用完成。接下来是指令声明:

app.directive('myTable', function () {
    return {
        restrict: 'E',
        scope: { rows: '=' },
        link: function (scope, element, attrs) {
            // At this stage you can use the scope.rows value
            // which will contain the result from your AJAX call
        }
    };
});

请注意 scope: { rows: '=' },它允许将复杂参数从父作用域传递到指令,而不仅仅是示例中的字符串值。

执行link函数后,您可以使用scope.rows变量,该变量将包含从$resource检索到的实际数据。

关于angularjs - 休息调用后,Angular JS 指令未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28519788/

相关文章:

javascript - Angular 模型未针对对象的内部属性进行更新

javascript - 将附加参数传递给指令回调 Angular js

javascript - 如何使用 angularjs 中的字符串从工厂内调用函数

javascript - AngularJs ngRepeat系列?

php - angularjs路由,如何检查模板文件是否存在

angularjs - Angular2 RC5 教程 : Can't bind to 'ngModel' since it isn't a known property of 'input'

javascript - Node.js fs ENOENT 错误

node.js - 只是无法解决 CORS 问题

javascript - 未捕获的类型错误 : Cannot set property 'isEditMode' of undefined

angularjs - 无法读取未定义的属性 'impl'