angularjs 自定义指令不起作用

问题描述 投票:0回答:3

我像这样将自定义属性添加到我的应用程序中

'use strict';

myApp.directive('orientable', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs, controller) {
      element.bind("load", function (e) {
        console.log('test');
        /* my code is here*/

      });

    }
  }
});

在我看来像这样添加使用此

<div class="xyz" orientable></div>

但它没有调用链接函数,我做错了什么。

angularjs directive
3个回答
0
投票

你的小提琴不起作用。

不知道你想做什么,但是这个有效。

只需在

link
功能上做你想做的事即可。


0
投票

正如兰特所说,你的小提琴坏了。它没有加载角度或其依赖项(cookie 和动画)。另一方面,div 没有

load
。只需将您的日志移出
element.bind...

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

myApp.controller('myctrl', ['$scope','$rootScope',function($scope,$rootScope)
{
    //controller logic
}]);

myApp.directive('orientable',function () {       
    return {
        restrict:'A',
        link: function(scope, element, attrs, controller) {   
            console.log('yahan');               
            element.addClass("vertical");             
        }
    }
});

您还有

restrict: 'E'
,它是元素名称,如
<orientable></orientable>

您将其作为属性,因此需要将

restrict
更改为
A

您可以执行

restrict: 'EA'
并能够使用任一方法(属性或元素名称)。


0
投票

我也遇到过同样的问题。最后我知道我们需要加载“orientable”作为 ng-app 的 DI 模块。我们需要添加这个“可定向”。

© www.soinside.com 2019 - 2024. All rights reserved.