内部范围和attrs变量/对象是什么?

时间:2014-09-17 04:21:09

标签: javascript jquery angularjs object

scopeattrs变量中定义了什么?怎么看那里有什么?

另外,我如何使用scope变量写入字段IDscopeID

另外,为什么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>

1 个答案:

答案 0 :(得分: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>