javascript - distinguish scope method of custom directives angularjs -
javascript - distinguish scope method of custom directives angularjs -
so have plunker
see, see utilize scope.click
methods on link has ng-click function on , defined scope.click = function() {}
within 'mydirective' custom directive.
the question when click link why refer sec element of custom directive why can't refer both elements? how can accomplish , how distinguish both elements within scope.click
function on 'mydirective' custom directive ?
the problem is, have no isolated scope defined in directives. means hat both directives share scope controller. using directive 2 times, define scope.click
event twice, overwrite scope.click
of first element. additionally overwrite ng-click of <a>
tag.
class="snippet-code-js lang-js prettyprint-override">var app = angular.module('myapp', []); app.controller('mainctrl', function($scope) { $scope.click = function() { console.log("inside controller"); } }); app.directive('mydirective', function() { homecoming { restrict:'ea', scope: {}, template: "<div ng-click='click()'>click me</div>", link:function(scope,elm, attr) { scope.click = function() { console.log("inside directive " + attr['id']); } } } });
class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myapp" ng-controller="mainctrl" ng-init="test=1;"> <a href='javascript:;' ng-click="click()">click link</a> <my-directive id="elm"> </my-directive> <my-directive id="elm2"> </my-directive> </div>
in illustration define isolated scope scope: {}
. each directive has own scope. additionally define click()
each scope.
update
if want execute function of directive when clicking on element outside of directive in way. however, not nice solution. think problem solve otherwise.
class="snippet-code-js lang-js prettyprint-override">var app = angular.module('myapp', []); app.controller('mainctrl', function($scope) { $scope.click = function($event) { $scope.activateelement[$event.target.id](); } $scope.activateelement = array(); }); app.directive('mydirective', function() { homecoming { restrict:'ea', link:function(scope,elm, attr) { scope.activateelement[attr['forid']] = function() { console.log("inside directive " + attr['forid']); } } } });
class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myapp" ng-controller="mainctrl"> <a href='javascript:;' ng-click="click($event)" id='elm'>click link</a> <!-- when click above link, run click methods under 'elm' custom directive --> <my-directive forid="elm"> </my-directive> <a href='javascript:;' ng-click="click($event)" id='elm2'>click link</a> <!-- when click above link, run click methods under 'elm2' custom directive --> <my-directive forid="elm2"> </my-directive> </div>
javascript angularjs
Comments
Post a Comment