【问题标题】:"require" DDO option of Angular directive does not throw an error when it shouldAngular 指令的“require” DDO 选项在应该抛出错误时不会抛出错误
【发布时间】:2015-04-28 02:46:12
【问题描述】:

如果这很明显,请原谅我,但我只是在学习。

我一直在关注this article,试图理解 AngularJS 中的指令。

docs specify 表示,如果未找到引用的指令,则指令的 DDO 的 require 选项应抛出错误。

我似乎无法让它引发错误 - 这是我的代码(我使用的是 v1.3.13)

test.html

<body ng-app="Test">
    <dir />
</body>

test.js

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

test.directive('dir', function() {
    return {
        require: '99 red baloons',
        restrict: 'E',
        template: '<div>this should not work</div'
    };
});

(这里是对应的jsfiddle

似乎一切正常,$compile 函数没有抱怨,指令被拾取并在 DOM 中呈现就好了。我错过了什么?

谢谢!

编辑

这似乎是 Angular 中的一个错误,here's 要匹配的问题

【问题讨论】:

    标签: javascript angularjs angularjs-directive require


    【解决方案1】:

    所以这里存在几个问题,一个是代码,另一个(在我看来)是 Angular 团队实现 Require 功能的不正确方式,我们需要解决这个问题。

    为了使您的代码正常工作,您需要在链接函数中引用所需的控制器,直到您这样做,它才会检查控制器是否存在于前面的元素中并且不会抛出异常,另一个问题是您需要在指令中构建所需的控制器才能使链接 api 工作。

    不幸的是,角度团队已经创建了默认行为,我不同意,在指令的编译/渲染阶段,当它确定需要什么时,它仍然会渲染有错误的指令的嵌入/模板.因此,即使应用程序抛出异常,它看起来也能正常工作。为了解决这个问题,一旦成功加载,您可以将子指令的链接函数中的作用域属性设置为 true,您将在模板中的 ng-show 中使用该属性。如果由于不满足所需的控制器而导致链接无法运行,则不会显示模板。

    这是一个工作示例:

    <body>
        <div main>
        </div>
    
        <script type="text/ng-template" id="main.html">
          <span>Hello, {{name}}!</span>
          <button ng-click="mainCtrl.log('Log Log Log, wondeful LOG!!!')">LOG</button>
          <sub></sub>
        </script>
    
        <script type="text/ng-template" id="sub.html">
          <div ng-show="loaded">{{name}} this should not work</div><div ng-transclude></div>
        </script>
    </body>
    

    使用相应的javascript,只需将所需的控制器更改为假名即可在控制台中查看错误:

    var app = angular.module('myApp', []);
    
    app.directive('main', function() {
      return {
        restrict: 'A',
        transclude: true,
        controllerAs: 'mainCtrl',
        controller: function($scope) {
          $scope.name = 'World';
          this.log = function(test) {
            console.log(test);
          };
        },
        templateUrl: 'main.html'
      }
    });
    
    app.directive('sub', function() {
      return {
        require: '^main',
        restrict: 'E',
        transclude: true,
        templateUrl: 'sub.html',
        link: function(scope, element, attrs, requiredCtrl) {
          requiredCtrl.log("heck ya!")
          scope.loaded = true;
        }
      };
    
    });
    

    【讨论】:

    • 感谢您指路 - 只有在 DDO 中没有链接功能时才会发生这种情况
    猜你喜欢
    • 2017-08-24
    • 2012-11-21
    • 2017-08-21
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多