javascript - Angular directive isolate scope: scope function won't execute -
i'm having trouble understanding how define functions used (or inside of) directive has isolate scope. in following code, why doesn't $scope.foo()
function execute? there correct way should approaching problem? i'm looking make button visible if user logged in, , thinking directive nice way encapsulate/isolate functionality.
<!doctype html> <html> <head> <script src="https://code.angularjs.org/1.4.2/angular.js"></script> <script> angular.module('myapp', []) .directive('myscopeddirective', function() { return { scope: {}, // <!-- isolate scope breaks things controller: function($scope) { // isolate scope prevents function being executed $scope.foo = function() { alert('myscopeddirective / foo()'); }; } }; }); </script> </head> <body> <div ng-app="myapp"> <!-- button doesn't work unless isolate scope removed --> <button my-scoped-directive ng-click="foo()">directive container - foo()</button> </div> </body> </html>
it's not working because using 2 directives in different scopes, ngclick
, myscopeddirective
. need create template directive , call click function so:
<!doctype html> <html> <head> <script src="https://code.angularjs.org/1.4.2/angular.js"></script> <script> angular.module('myapp', []) .directive('myscopeddirective', function() { return { restrict: 'ae', // can defined element or attribute scope: {}, // call click function directive template template: '<button ng-click="foo()">directive container - foo()</button>', controller: function($scope) { $scope.foo = function() { alert('mydirective / foo()'); }; } }; }); </script> </head> <body> <div ng-app="myapp"> <my-scoped-directive></my-scoped-directive> </div> </body> </html>
working plunker
Comments
Post a Comment