Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Directives not working

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 :)

like image 357
Pedro M. Silva Avatar asked Jan 14 '13 20:01

Pedro M. Silva


People also ask

What is directives in AngularJS?

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.

What are the three types of directives in Angular?

The three types of directives in Angular are attribute directives, structural directives, and components.

What are directives in Angular 7?

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.


1 Answers

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.

like image 139
Mark Rajcok Avatar answered Oct 13 '22 17:10

Mark Rajcok