Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference of function(javascript) vs scope.function(angular function) defined in controller

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.

like image 227
Satyam Koyani Avatar asked May 25 '26 17:05

Satyam Koyani


1 Answers

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.

like image 126
Yngve B-Nilsen Avatar answered May 28 '26 06:05

Yngve B-Nilsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!