简体   繁体   中英

Calling scope.$parent.function outside the directive in a controller

i have this function inside my directive link function:

scope.$parent.resetData(){
   scope.data = '';
}

in my html:

<ul ng-model="selectedObject">
  <li>{{ object.label }}</li>
</ul>
<button ng-click="resetData()">reset!</button>
<directive data={{ selectedObject.dataset }}></directive>

and in my app.controller

$scope.$watch('selectedObject', function(){
   $scope.resetData(); //this cant be used 
});

i cant use $scope.reset() in the controller scope, is there a way to be able to re-use that function in the simpliest way instead of doing a factory/service for this dataset?

Feed the directive selectedObject instead of selectedObject.dataset and let it manage the reset internally.

It would be more encapsulated, which would be good. If changing selectedObject always resets the data, thinking of the directive as a component and having the logic inside makes it more self-contained. That way outside code doesn't have to worry about helping the directive do its job.

If you insert a ctrl argument to the link function You can talk directly to the parent controller

    link: function(scope, el, attr, ctrl) { 
        scope.isSmall = function(){
            return ctrl.isSmall();
        };
     }

At least that's how it works for me

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