Saturday 15 June 2013

angularjs - Extending a controller function within directive -



angularjs - Extending a controller function within directive -

i have cancel function in controller want pass or bind directive. function clears form. this:

app.controller('myctrl', ['$scope', function($scope){ var self = this; self.cancel = function(){... $scope.formname.$setpristine(); }; }]); app.directive('customdirective', function() { homecoming { restrict: 'e' scope: { cancel : '&oncancel' }, templateurl: 'form.html' }; });

form.html

<div> <form name="formname"> </form> </div>

however, $setpristine() don't work controller don't have access on form dom. possible extend functionality of controller's cancel within directive add together $setpristine()?

some suggested using jquery select form dom, (if it's way) how exactly? there more angular way of doing this?

since <form> within directive, controller should have nil it. knowing break encapsulation, i.e. leak implementation details directive controller.

a possible solution pass empty "holder" object directive , allow directive fill callback functions. i.e.:

app.controller('myctrl', ['$scope', function($scope) { var self = this; $scope.callbacks = {}; self.cancel = function() { if( angular.isfunction($scope.callbacks.cancel) ) { $scope.callbacks.cancel(); } }; }); app.directive('customdirective', function() { homecoming { restrict: 'e' scope: { callbacks: '=' }, templateurl: 'form.html', link: function(scope) { scope.callbacks.cancel = function() { scope.formname.$setpristine(); }; scope.$on('$destroy', function() { delete scope.callbacks.cancel; }); } }; });

use as:

<custom-directive callbacks="callbacks"></custom-directive>

i'm not sure ok either though...

angularjs

No comments:

Post a Comment