未调用 AngularJS 链接函数 [英] AngularJS Link function not called

查看:29
本文介绍了未调用 AngularJS 链接函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写我的第一个 AngularJS 指令:一个涉及 link 函数的指令.指令正在加载,但是当我在我的页面中使用它时,link 函数没有被调用.


这是小提琴:http://jsfiddle.net/jCUSh/115/

这是 HTML:

<google-maps-symbol></google-maps-symbol>

和 JavaScript:

var appModule = angular.module('biApp', []);appModule.directive('googleMapsSymbol', function () {console.log("指令已运行");返回 {链接:函数(范围,元素,属性){console.log("链接被调用");}};});


我敢打赌我做错了一些简单的事情.

解决方案

angular 的默认设置是假设指令是 attributes,而不是 elements!您正在使用指令作为元素,因此您需要使用限制来指定它.更新后的代码如下:

appModule.directive('googleMapsSymbol', function () {console.log("指令已运行");返回 {限制:'E',链接:函数(范围,元素,属性){console.log("链接被调用");}};});

注意限制:'E',.祝你好运!

更新你的小提琴: http://jsfiddle.net/j8ZZ4/

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.

解决方案

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/

这篇关于未调用 AngularJS 链接函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆