1

A custom directive was created in AngulerJS 1. It has in isolate scope, and is data-aware (gets data from server API). Its definition looks like this:

var dirJobView = function ($location, serviceData) {
    return {
        restrict: 'A',
        templateUrl: '/app/views/Jobs/Item.html',
        scope: {
            itemid: "@"
        },
        controller: ['$scope', function ($scope) {
            scope = $scope;
            // does not work - data is not displayed in view:
            serviceData.get('jobs', scope.itemid).then(function (data) {
                scope.dataJobView = data;
            });
        }],
        link: function (scope, elem, attrs, ctrl) {

        }
    };
}

The above is not working - the data is loaded, but the view does not display it. To be more exact, it only displays it if I force "Clear Cache and Hard Reload" in the browser.

However, it works perfeclty well if I move the service call to the link function like so:

var dirJobView = function ($location, serviceData) {
    return {
        restrict: 'A',
        templateUrl: '/app/views/Jobs/Item.html',
        scope: {
            itemid: "@"
        },
        controller: ['$scope', function ($scope) {
            scope = $scope;

        }],
        link: function (scope, elem, attrs, ctrl) {
            // Moved from controller, now works
            serviceData.get('jobs', scope.itemid).then(function (data) {
                scope.dataJobView = data;
            });
        }
    };
}

From what I understand, the link function is intended for manipulating the DOM, and the controller is meant to invoking the services and defining the behaviour. The call to service data should be placed in the controller, shouldn't it?

Why is the above works the way it does?

1
  • just try scope.$apply() in the controller after the scope.dataJobView = data and check if anything changes. Commented Oct 22, 2016 at 8:33

1 Answer 1

0

Found the problem. Was missing a "var" in "scope = $scope;". The controller def body should be like this:

controller: ['$scope', function ($scope) {
            var scope = $scope;
            // does not work - data is not displayed in view:
            serviceData.get('jobs', scope.itemid).then(function (data) {
                scope.dataJobView = data;
            });
        }],
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.