Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Link function not called

I'm trying to write my first AngularJS directive: one involving the link function. The directive is being loaded, but when I use it in my page the link function is not called.


Here's the fiddle: http://jsfiddle.net/jCUSh/115/

Here's the HTML:

<div ng-app="biApp">
    <google-maps-symbol></google-maps-symbol>
</div>

and the JavaScript:

var appModule = angular.module('biApp', []);

appModule.directive('googleMapsSymbol', function () {
    console.log("Directive was run");
    return {
        link: function (scope, elem, attrs) {
            console.log("Link was called");
        }
    };
});


I'll bet I'm doing some simple thing wrong.

like image 798
jcarpenter2 Avatar asked May 01 '14 16:05

jcarpenter2


People also ask

What is link function in AngularJS?

Link: The link function deals with linking scope to the DOM. Using Code for Compile. While defining a custom directive we have the option to define a link against which either we can define a function or we have the option to assign an object which will have pre & post function.

What is compile and link in AngularJS?

Compile function: It is used for template DOM Manipulation and collect all of the directives. Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned.

What is$ compile in AngularJS?

Overview. Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. The compilation is a process of walking the DOM tree and matching DOM elements to directives.


1 Answers

The default for angular is to assume that directives are attributes, not elements! You are using a directive as an element so you need to specify this with the restrict. The updated code reads:

appModule.directive('googleMapsSymbol', function () {
    console.log("Directive was run");
    return {
        restrict: 'E',
        link: function (scope, elem, attrs) {
            console.log("Link was called");
        }
    };
});

Note the restrict: 'E',. Best of luck!

Updating your fiddle: http://jsfiddle.net/j8ZZ4/

like image 140
drew_w Avatar answered Oct 21 '22 02:10

drew_w