javascript - Accessing function on scope in directive link function -
i have directive setup follows:
angular.module("app", []).directive("mydirective", function(){ return { scope: {}, link: function($scope){ $scope.myfunction = function(){ //do dom manipulation } } } });
and in html have
<div my-directive> <a href="" ng-click="myfunction()">click me</a> </div>
when click "click me" nothing prints console, however, if remove scope property or change scope:true
works expected. know has isolate scope don't understand what's going on. want have isolate scope going modular directive use in many different project.
note: i'm using angular 1.4.6
update: function needs dom manipulation. why it's in link function.
the reason isn't working because how link
being used.
since elements exist within directive before exists, elements aren't compiled information inside link
. want need put elements in template
or templateurl
can compiled against link
.
here example:
angular.module("myapp", []).directive("mydirective", function() { return { scope: {}, template: '<a href="" ng-click="myfunction()">click me {{value}}</a>', link: function(scope) { scope.value = 'value here'; scope.myfunction = function() { console.log('you here.'); } } } });
<script data-require="angular.js@1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script> <div ng-app="myapp"> <div my-directive> <a href="" ng-click="myfunction()">click me {{value}}</a> </div> </div>
Comments
Post a Comment