Mohaideen
Mohaideen

Reputation: 209

How to update the scope value without using $watch

I have using custom directive

<users stats="stats"></users>

When we change the scope object from main controller, i have updating directive scope value also

app.directive('users', function(){
    var directive = {};
    directive.restrict = "E";
    directive.templateUrl = "templates/partials/users_stats.html";
    directive.scope = {stats:'='};
    directive.controller = "userStatsCtrl"
    return directive;
});

So, Inside the directive controller, i am doing some func. like

app.controller("userStatsCtrl", function($scope){
    $scope.$watch('stats', function(newValue) {
      if (angular.isDefined(newValue)) {
        .....
      }
    });
})

So here, i am using $watch to listen the scope, If it is update, I will do the some perform.

my question is, I dont want to use watch to listen the scope, If scope gets updated, i need to do some perform.

So how to update scope value without using scope.$watch

Upvotes: 1

Views: 411

Answers (2)

Vasant Gopalakrishnan
Vasant Gopalakrishnan

Reputation: 51

how about trying:

<users stats="stats" ng-change="onUserStatChange($event)"></users> 
                           or
<users stats="stats" ng-blur="onUserStatChange($event)"></users>

and then in controller:

$scope.onUserStatChange = function(event) {
    //event.whatever
}

Upvotes: 0

Aravinder
Aravinder

Reputation: 503

When ever "scope.stats" value get changed in your main controller, you can broadcast an event and receive the same event in your directive and do operation what ever you want. Example code for broadcast an event:

$scope.$broadcast('yourEventName');

Receive an event in directive:

$scope.$on('yourEventName', function(){

});

Upvotes: 0

Related Questions