angularjs - In Angular, is there a way to communicate imperatively to a directive? -
what know
i have custom directive isolate scope.
"outside", can communicate to directive using declarative bindings (via @
, =
bindings).
directive can communicate to outside using either declarative bindings (=
) or imperative callbacks (&
).
what i'd know
is there imperative way communicate to directive?
example
say have <edit-profile>
directive. i'd expose method reset()
, owner of directive can reset directive (imperatively).
here's i'd it:
<edit-profile on-save="..."></edit-profile> <button ng-click="editprofile.reset()"> reset </button>
and here's directive:
app.directive("editprofile", function() { return { restrict: "e", scope: { onsave: "&" }, template: ` <input type="text"> <button ng-click="onsave()"> submit </button> `, controller: function($scope) { $scope.reset = function(){ ... }; } }; });
what ways can achieve kind of "imperative" approach directive communication?
you can use same technique 1 used 'form' directive: expose controller of directive parent scope. here's basic example:
angular.module('directives').directive('foo', function() { return { scope: { name: '=' }, controller: function($scope) { this.sayhello = function() { $scope.hello = 'hello'; }; $scope.name = this; }, template: '<div>{{ hello }}</div>' }; });
and unit test, showing how link outside of directive can call function on directive controller when clicked:
describe('foo', function() { var elm, scope; beforeeach(module('directives')); beforeeach(inject(function($rootscope, $compile) { elm = angular.element( '<div><foo name="bar"></foo><a href="" ng-click="bar.sayhello()">say hello</a></div>'); scope = $rootscope; $compile(elm)(scope); scope.$digest(); })); it('should hello', function() { var = elm.find('a'); var div = elm.find('foo'); expect(div.text()).not.tocontain('hello'); a.triggerhandler('click'); expect(div.text()).tocontain('hello'); }); });
Comments
Post a Comment