【问题标题】:Directive never gets called angularjs指令永远不会被称为 angularjs
【发布时间】:2015-04-01 06:28:24
【问题描述】:

我们正在创建一个指令,用于在用户单击按钮时增加和减少文本框中的数字。

这是我的自定义指令的代码。

var CEDirectives = angular.module('App.customnumberdirectives', [])
.directive('ngcustomNumber', ['$compile', function ($compile) {
var TEMPLATE_URL = '/customnumber/index.html';
var tem = '<div class="wrapper">' +
          '  <input type="text" data-ng-model="{{model}}" data-ng-blur="onBlurHandler()">' +
          '  <button ng-click="Increase()" style="cursor:pointer; background-color: transparent">INC</button>' +
          '  <button ng-click="Decrease()" style="cursor:pointer; background-color: transparent">DEC</button>' +
          '</div>';

// Set the default template for this directive
$templateCache.put(TEMPLATE_URL,tem);

return {
    restrict: "E",
    scope: {
        model: '@',
        onblurevent: '&'
    },
    replace: true,
    templateUrl: function (element, attrs) {
        return attrs.templateUrl || TEMPLATE_URL;
    },
    link: function (scope, element, attributes) {

        scope.onBlurHandler = function () {
            if (scope.onblurevent) {
                scope.onblurevent();
            }
        };

        scope.Increase = function () {
            alert('Inc');
        };
        scope.Decrease = function () {
            alert('Dec');
        };
    }
};
} ]);

在 html 视图中:-

 <ngcustomNumber model="weight" onblurevent="Save"></ngcustomNumber>

(1) 控制台没有错误。

(2) 尝试将警报放在指令的顶部。没有警报消息出现。

提前致谢!

【问题讨论】:

  • 你是否在 html 中应用了 ngApp
  • 是的。它在 HTML 标记中。
  • App.customnumberdirectives 是您的模块名称,只是为了确认?
  • 您是否将'App.customnumberdirectives' 的引用\依赖添加到您的主应用模块中。
  • 你的指令在浏览器中加载了吗?

标签: javascript jquery html angularjs angularjs-directive


【解决方案1】:

试试这个:

<ngcustom-number model="weight" onblurevent="Save"></ngcustom-number>

【讨论】:

  • 工作。但是我可以知道以类似的方式编写指令是强制性的吗?
  • 你设置了restrict:'E',这意味着只允许元素。使用AE,否则如果你想用作属性
  • 由于 HTML 不区分大小写,我们在 DOM 中以小写形式引用指令,通常在 DOM 元素上使用破折号分隔的属性(例如 ng-model)。 docs.angularjs.org/guide/directive#normalization
【解决方案2】:

因为你的编译没有以正确的方式完成。你必须确保给定的范围是 ON 模板。为了检查它,你可以在模板中打印范围 ID。你知道每个范围都有它的 ID,所以如果指令范围和模板scope id 不一样,你的问题在里面,解决方法是:

用正确的方式编译它。将指令的范围传递给它。 $compile 服务:$compile(template)(directiveScope);

您可以控制范围,并会看到我正在谈论的字段

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 2020-11-18
    • 2019-08-01
    • 2012-10-27
    • 2013-10-12
    相关资源
    最近更新 更多