0

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?

2
  • I guess using $scope.$watch() on $scope.project is the right way to go... Commented Feb 13, 2014 at 7:30
  • ...or not even $watch(), if data bindings in my view are correctly set up. #StartingToThinkWithAngularJS Commented Feb 13, 2014 at 7:39

1 Answer 1

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.