I'm using AngularJS in a project of mine, and I wanted to try creating directives. I already followed several tutorials and I can't see where I'm doing it wrong. Even worst, it doesn't shows up any error or warning message, but it also does not executes the directive's function. Right now, my code is pretty much this:
angular.module('components', []).directive('ngxOnshow', function() {
return {
restrict: 'A',
link: function(scope, element, attrs){
console.log("hello world")
//Resto do código da função
}
};
});
var module = angular.module('app', ['components']);
In the body of the HTML page I have this:
<body ng-autobind ng-app="app">
But then, when I use the directive, it does not work.
<div ng-show="showApp == true" ngx-onshow="showAppBar()">
</div>
The rest of the application works just fine, the bindings, the default directives, everything except this. Perhaps I'm missing something?
Thanks, Scorch :)
Directives are markers on the DOM element which tell AngularJS to attach a specified behavior to that DOM element or even transform the DOM element with its children. Simple AngularJS allows extending HTML with new attributes called Directives.
The three types of directives in Angular are attribute directives, structural directives, and components.
Directives are classes that add additional behavior to elements in your Angular applications. Use Angular's built-in directives to manage forms, lists, styles, and what users see. See the live example / download example for a working example containing the code snippets in this guide. Used with a template.
Use '&' to allow a directive to execute an expression/function defined in the parent scope. $observe an interpolated isolate scope attribute (i.e., one defined with '@' that contains {{}}
) to determine when it changes:
myApp.directive('ngxOnshow', function () {
return {
restrict: 'A',
scope: {
showApp: '@',
ngxOnshow: '&'
},
link: function (scope, element, attrs) {
console.log("inside link function")
attrs.$observe('showApp', function (newValue) {
newValue === "true" && scope.ngxOnshow()
})
}
};
});
newValue is compared with "true"
not true
because interpolated values are always strings.
HTML:
<div ng-show="showApp == true" show-app="{{showApp}}" ngx-Onshow="showAppBar()">
Fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With