简体   繁体   中英

Angular.js $scope.$on initial value

I'm using angular.js $scope.$on for listening for events from my service(event got triggered on service data change).

I use the following code snippet:

$scope.people = contacts.people;
$scope.$on('contacts-changed', () => {
    $scope.people = contacts.people;
});

Is there any way to extend angular to avoid the first line and trigger $scope.$on('contacts-changed') or similar by default on the time of event bind? I was looking in angular.js decorators but not sure how can I decorate $scope to add $scope.$bind or similar method

Ideas?

Sometimes the solution is so simple, but you need to think outside of the box. Move the event callback block into a function and just run it when the controller loads, after the event binding.

See this:

function handlePeople() {
    $scope.people = contacts.people;
}
$scope.$on('contacts-changed', handlePeople);
handlePeople();

You can also keep the original code and do a trigger manually.

Temporally went with the following solution:

$rootScope.$bind = (bindName, bindHandler) => {
    $rootScope.$on(bindName, bindHandler);
    bindHandler();
};

But I'd want to replace it so I could use $scope instead of $rootScope and without defining this in each $scope... I could try to use $scope._ proto _ but it seems _ proto _ is deprecated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM