【问题标题】:Using a $resource-based data model with controller and directives使用带有控制器和指令的基于 $resource 的数据模型
【发布时间】:2014-02-14 18:28:03
【问题描述】:

我为我的项目数据创建了一个“模型”*,如下所示:

angular.module('myapp').factory("projectModel", function ($resource) {
    return $resource(
        "/api/projects/:id",
        { id: "@id" },
        {
            "update": { method: "PUT" }
        }
    );
});

想要wait-until-everything-has-loaded-before-displaying-anything behavior using resolve in the routing,相反我很乐意让 UI 和数据在它准备好时弹出。

如果在我的控制器中拥有$scope 上的项目数据会很好,但由于projectModel 返回一个promise,而不是数据,我需要做类似的事情:

angular.module('myapp').controller('EditorCtrl', function ($scope, projectModel) {

    projectModel.get({}, { 'id': session.projectId },
        function (successResponse) {
            // success callback
            $scope.project = successResponse;
        },
        function (errorResponse) {
            // failure callback
            console.log(errorResponse);
        }
    );

数据会在指令中渲染,但是由于指令的link方法在设置$scope.project之前执行,所以我没有数据可以及时渲染。我可以包含 projectModel 作为对指令的依赖,但这感觉很脏。

让指令可以访问项目数据的正确方法是什么?

*额外问题:我应该将我的$resource 派生服务视为 MVC 模型,还是令人困惑?如果是,使用辅助方法等扩展模型的最佳方法是什么?

【问题讨论】:

  • 我想在$scope.project 上使用$scope.$watch() 是正确的方法...
  • ...甚至$watch(),如果我认为数据绑定设置正确的话。 #StartingToThinkWithAngularJS

标签: javascript angularjs ngresource


【解决方案1】:
$scope.$watch('projectList', function (newVal, oldVal) {
                    if (newVal !== oldVal ) {
                    angular.forEach($scope.projectList, function (row) {
                          row.getName = function () {
                            return splitName(row.community_name);
                          };
                       });
                    }
                }, true);

是的,你说得对,我有类似的问题,你可以通过观察 $scope.project 中的变化来做到这一点,你可以将代码放入其中。当 $scope.projectList 中有值时,检查上面的示例以动态更新 ng-grid

【讨论】:

    猜你喜欢
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多