angularjs - 指令的隔离范围

标签 angularjs angularjs-directive angularjs-scope

我在理解 Angular 指令中的独立作用域时遇到了一些麻烦。我已经阅读了官方文档,观看了很多有关该主题的视频,所以现在我知道它们的用途是什么,但我不确定如何使用它们。

这是一个简单的例子。
我创建了一个名为 searchBox 的指令(参见 full source and demo )

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

myApp.directive('searchBox', function($timeout) {
  return {
    restrict: 'A',
    scope: true,
    link: function(scope, element) {                
      scope.open = false;

      // Show search input
      scope.showInput = function() {
        scope.open = true;

        // Focus the input
        $timeout(function() {
          element.find('input').focus();
        }, 0);
      };

      // Hide search input
      scope.hideInput = function() {
        scope.open = false;
      };
    }
  }
});

这实际上按预期工作。但是,我想隔离指令的范围,但是如果我将 scope: true 更改为 scope: {} (请参阅 full source and demo ))它不再有效,但我在控制台中看不到任何错误。

我确定这是我做错的基本问题,但我真的希望有人能开阔眼界,帮助我理解这一点。

最佳答案

Got it working .

问题是指令应该包含它自己的模板(或者有 transclude option set to true ),因为你正在包装其他元素。

如果在 search-box 指令的模板内定义了其他指令(如 ng-click 或 ng-blur),它们将根据搜索框 $scope 进行评估。但是,如果没有模板,它们会冒泡到父 $scope(在这种情况下,它没有函数 showInput() 或 hideInput() 等)。

如果您不想在指令的声明中包含 html 字符串,您可以使用 templateUrl 选项来引用外部模板。

关于angularjs - 指令的隔离范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19937458/

相关文章:

javascript - 如何检测 Angular 应用程序是否已从 Angular 外部初始化?

angularjs - $scope 与此性能

javascript - AngularJS SPA 路由获取 URL 为 "/#!"而不是 "#"

angularjs - Protractor 如何测试select2

javascript - 我可以在自定义 Angular 元素的 html 标记中传递 args 吗?

javascript - 执行特定时间的函数 - AngularJs

angularjs - 使用 jquery-menu-aim 设置子范围的值

angularjs - karma state go 无法解析 "..."

javascript - 设置 AngularJS 元素的值

javascript - 如何在angular js中切换orderby