Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
@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. –  Yngve B. Nilsen Jul 23 at 6:37

2 Answers 2

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.

share|improve this answer

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.

share|improve this answer
    
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? –  Satyam Koyani Jul 23 at 6:49
    
Not exactly. The first button will fail with a Javascript error, because the function does not exist outside the controller. –  Yngve B. Nilsen Jul 23 at 6:52
    
@SatyamKoyani Please remember to mark an answer as correct –  Yngve B. Nilsen Jul 23 at 10:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.