1

I am very new to angularjs and i am not sure if this is the right approact I am trying do similar math so I was thinking of putting it in directive

myApp.directive('getDistance',function(Auth){
    var R = 6371;


    return {
        restrict: 'AE',
        template: '{{distance}}',
        scope: {
            value: '=value',
            maxValue: '=max-value'
        },
        link : function(scope, element, attr) {
            $scope.$apply(function(){
               $scope.distance = scope.maxValue - scope.value;
            });

        }
    };

});

Same directive will be used in the same page multiple times and I think every directive will use the same distance. How can i fix this or what will be a better approach?

1
  • 1
    So what exactly is the problem (I can see that your directive can't work in the current form). Is it your issue, to make it work? Commented Nov 17, 2014 at 19:26

1 Answer 1

2

There are several issues with your directive. You can fix them and also improve code at the same time.

First of all maxValue: '=max-value' is not correct isolated scope property definition. You must use camelCase for property/attribute names: maxValue: 'maxValue'.

Having fixed that, you can then remove names on the right all together and use = symbol, since scope names are the same at corresponding attributes.

And finally in link function you referred wrong scope variable $scope. Final directive would look like this:

myApp.directive('getDistance', function(Auth) {
    var R = 6371;

    return {
        restrict: 'AE',
        template: '{{distance}}',
        scope: {
            value: '=',
            maxValue: '='
        },
        link: function(scope, element, attr) {
            scope.distance = scope.maxValue - scope.value;
        }
    };    
});

Demo: http://plnkr.co/edit/3pbe9Z3e40JT5far4ijK?p=preview

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

4 Comments

this is exactly what i want, but when i am putting it in it is throwing an error. FYI i am using ionic framework which shouldnt matter though. Error: [$injector:unpr] Unknown provider: getDistanceProvider <- getDistance
Are you sure you don't inject getDistance anywhere, in controller for example? You should not.
Thank you so much, yes i was injecting in controller, i thought my view wont have access to the directive if i dont inject in controller.
I see, glad you figured it out.

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.