AngularJS指令的链接函数未定义

Ros*_*mov 2 javascript angularjs

我正在尝试按照此链接的教程构建一个简单的指令:http://slides.com/djsmith/deep-dive-into-custom-directives(我认为它是幻灯片11和12,没有编号).

因为它只显示了JavaScript部分和HTML部分的一小部分(只是文本输入).我创建了自己的html页面如下:

<!DOCTYPE html>
  <html>
    <head>
      <title>Directives</title>
      <script src="Scripts/angular.min.js"></script>
      <script src="Scripts/angular-route.min.js"></script>
      <script src="Scripts/app.js"></script>
    </head>
    <body ng-app="MyDirectives" ng-controller="DirectivesController">
     <input type="text" select-all-on-focus />
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

带有模块和控制器的JS文件(只是一个空的,我认为没有一个可能是问题)和指令:

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

myModule.controller('DirectivesController', ['$scope', function ($scope) {

}]);

myModule.directive('selectAllOnFocus', function () {
    return {
        restrict: 'A', 
        link: function linkFn (scope, element, attrs) {
            element.mouseup(function (event) {
              alert("Lost focus!");
              event.preventDefault();
            });
            element.focus(function () {
              element.select();
              alert("Focused!");
            });
        }
      }
});
Run Code Online (Sandbox Code Playgroud)

Chrome控制台上显示的错误是:

TypeError:undefined不是一个函数在linkFn at j at f at f at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at US $ get.h. $ apply at http://

链接功能似乎有问题.

Cod*_*gue 5

AngularJS的jqLit​​e实现没有友好的click,mouseup等方法.你应该使用.on代替:

myModule.directive('selectAllOnFocus', function () {
    return {
        restrict: 'A', 
        link: function(scope, element, attrs) {
            element.on("mouseup", function (event) {
              alert("Lost focus!");
              event.preventDefault();
            });
            element.on("focus", function () {
              element.select();
              alert("Focused!");
            });
        }
      }
});
Run Code Online (Sandbox Code Playgroud)

jsFiddle