【问题标题】:What's inside scope, and attrs variables/objects?范围内有什么,以及 attrs 变量/对象?
【发布时间】:2014-09-17 04:21:08
【问题描述】:

scope 和 attrs 变量中定义了什么?怎么看里面有什么?

另外,我将如何使用scope 变量写入字段ID 和scopeID?

另外,为什么alert(scope.$id); 一直指向 001?我不是有2个应用程序吗?至少有 2 个独立的实体?

    <script>
        var firstApp = angular.module('firstApp', []);
        firstApp.directive('myFirstApp', function() {
            var variable = function(scope, element, attrs) {

                alert(scope.$id);
                $.each(elemArray, function(scope) {
                    $(this).on('click', function(scope) {
                        var id = $(this).attr("id");
                        scope.ID = $(this).attr("id");; // how to write to ID field here
                        alert($(this).attr("id"););
                    });
                });
            };
            return {
                restrict: 'AEC',
                link: variable
            };
        });
    </script>

    <my-first-app>
        <button id="a1">button 1</button>
        <button id="a2">button 2</button>
        <br />My ID: {{ ID }}
        <br />My Scope ID: {{ scopeID }}
    </my-first-app>
    <br />
    <my-first-app>
        <button id="b1">button 1</button>
        <button id="b2">button 2</button>
        <br />My ID: {{ ID }}
        <br />My Scope ID: {{ scopeID }}
    </my-first-app>

【问题讨论】:

  • 有一个名为 AngularJs 的 chrome 插件,通过它你可以看到范围内的内容。
  • 范围是继承的,除非另有说明。因此,这两个应用程序都继承了相同的父范围。如果您希望每个指令都有自己的子范围,请将“scope:true”添加到您的指令定义中

标签: javascript jquery angularjs object


【解决方案1】:

Demo Plunker

如果您想查看指令的“范围”上的内容,可以使用 angular.extend 将范围的属性浅复制到另一个对象,然后将该对象绑定到您的视图:

指令

   app.directive('myFirstApp', function() {
    return {
      restrict: 'AEC',
      link:function(scope, element, attr) {
         var inScope = {};
         angular.extend(inScope, scope);
         scope.inScope = inScope;
         scope.inAttr = attr;
      }
    }
  })

HTML

<div my-first-app>
  {{inScope }}
  {{inAttr}}
</div>

【讨论】:

  • 我相信restrict: 'A',应该是restrict: 'AEC',这样才能工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 2023-01-03
  • 1970-01-01
  • 2023-01-12
相关资源
最近更新 更多