3

I want to know the difference between declaration of this two function in angular controller

function demo() {                           
};               

scope.demo = function() {                    
};

Whether this two function are similar in performance or not?,Which one is the better option?

I know only one difference that watch can be applied to a function which is in the scope means angular directive or element can't call javascript function.

1
  • @LiviuM. That is not the same. function demo() is not the same as this.demo = function(). function demo() as the OP writes is a private function, and will never be accessible on the scope. Commented Jul 23, 2014 at 6:37

2 Answers 2

4

Consider the following controller:

app.controller('Home', function($scope){
    function thisIsAPrivateMethod(){
      alert('Hello world');
    }

    $scope.thisIsAPublicScopedMethod(){
       alert("I'm shown!");
    }

    thisIsAPrivateMethod(); // will trigger the alert everytime HomeController is instansiated
});

in the view:

<div ng-controller="Home">
    <button ng-click="thisIsAPrivateMethod()">I will not work</button>
<button ng-click="thisIsAPublicScopedMethod()">I should display an alert</button>
</div>

As you see, the private method is only accessible within the controller code itself.

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

3 Comments

Here you have called private method with angular directive "ng-click" so angular will find that private method in angular scope but It is not registered in scope so it will not be called.Am I correct?
Not exactly. The first button will fail with a Javascript error, because the function does not exist outside the controller.
@SatyamKoyani Please remember to mark an answer as correct
1

I think the only difference is the visibility of the function. The first one will be global, and the second one can only referred through a angular scope variable.

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.