javascript - $scope、$element 和 $attrs 变量到底如何相关(如果有的话)?

标签 javascript angularjs angularjs-directive

我编写了一个自定义的 Angular-js 指令,该指令在导航离开半填充且未保存的表单时要求用户确认。

它工作得很好,但我不确定我是否理解我在做什么。

代码如下所示:

HTML:

<input type="text" name="username" form-confirmation/>

app.js:

angular.module('myModule').directive('formConfirmation', formConfirm) 

function formConfirm() {
    return {
        restrict: 'A',
        link: function ($scope, $element, $attrs) {

            function conf(event) {

                if ($scope[$element.attr('name')].$dirty) {
                    if (confirm("You have unsaved changes! Are you sure you wish to leave this page?") !== true) {
                        event.preventDefault();
                    }
                }
            };

            $scope.$on('$locationChangeStart', conf);
        }
    }
}

我的问题:

1)我首先尝试使用 if($element.$dirty) 但这不起作用。 $element 与 $scope[$element.attr('name')] 有何不同?

2) $element、$attrs 和 $scope 之间有什么关系?

3)$element的attr方法从何而来?

最佳答案

它们与 DOM 中存在的元素相关,并且由于指令的存在(在本例中为 form-confirmation),导致 AngularJS 在该元素上执行编译操作。

所有这些项目的定义都可以在 directive documentation 中轻松找到。在为链接函数创建操作 DOM 的指令下:

  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values.
  • controller is the directive's required controller instance(s) or its own controller (if any). The exact value depends on the directive's require property.
  • transcludeFn is a transclude linking function pre-bound to the correct transclusion scope.

进一步分解您的问题:

  1. 我首先尝试使用 if($element.$dirty) 但这不起作用。如何 $element 与 $scope[$element.attr('name')] 不同吗?您正在根据 $element 上是否存在特定属性来为 $scope 对象上的属性建立索引。

  2. $element、$attrs 和 $scope 之间有什么关系?它们通过包含您的指令的已编译 DOM 元素相关。

  3. $element 的 attr 方法从何而来?由于 $element 是 DOM 元素的 jqLit​​e 包装器,因此它只是将实际 DOM 注释上存在的属性公开为 attr 属性。

我强烈建议您仔细阅读并消化我上面链接的指令文档。它包含丰富的知识,可以帮助您理解指令的工作原理,这是 AngularJS 的核心部分。

关于javascript - $scope、$element 和 $attrs 变量到底如何相关(如果有的话)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38314866/

相关文章:

javascript - 滚动时如何使 <li> 元素固定在 <ul> 元素的顶部和底部

javascript - 为 AngularJS 指令的根元素设置样式

angularjs - Angular 模态服务关闭问题

javascript - 找不到名称为 NameCtrl 的 Controller

javascript - Infragistics 使用 igTextEditor 过滤数字

javascript - 有没有办法用 JavaScript 检测移动 Safari 音频中断(耳机拔出)?

angularjs - 提供 url 到 angular $http.get/.post 的最佳方式

javascript - AngularJS - 包装指令

javascript - 在两个子组件之间共享一个方法(Angular)

javascript - jquery load() - 无法加载谷歌地图