Tom Söderlund
Tom Söderlund

Reputation: 4747

Using a $resource-based data model with controller and directives

I have created a "model"* for my Project data like this:

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

I don't want the wait-until-everything-has-loaded-before-displaying-anything behavior using resolve in the routing, instead I'm happy to let the UI and data pop up when it's ready.

It would be nice to have the project data on the $scope in my controller, but since projectModel returns a promise, not the data, I need to do something like:

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);
        }
    );

The data will be rendered in a directive, but since the directive's link method executes before $scope.project is set, I have no data to render in time. I could include projectModel as dependency on the directive but that feels dirty.

What's the correct way of making project data accessible to the directive?

*Bonus question: should I view my $resource-derived service as a MVC model, or is that confusing? If yes, what would be the best way of extending the model with helper methods etc?

Upvotes: 0

Views: 127

Answers (1)

rajmohan
rajmohan

Reputation: 1618

$scope.$watch('projectList', function (newVal, oldVal) {
                    if (newVal !== oldVal ) {
                    angular.forEach($scope.projectList, function (row) {
                          row.getName = function () {
                            return splitName(row.community_name);
                          };
                       });
                    }
                }, true);

Yes, you are right I had similar issue, you can do this by watch check for change in $scope.project and you can put the code inside it. Check the above example to update ng-grid dynamically when there is value in $scope.projectList

Upvotes: 1

Related Questions