HelpNeeder
HelpNeeder

Reputation: 6490

What's inside scope, and attrs variables/objects?

What is defined within scope and attrs variable there? How to see what's there?

Also, how would I use scope variable to write to fields ID and scopeID?

Also, why alert(scope.$id); keep pointing to 001? Don't I have 2 apps? At least 2 separate entities?

    <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>

Upvotes: 1

Views: 89

Answers (1)

Michael Kang
Michael Kang

Reputation: 52847

Demo Plunker

If you want to see what is on your directive's "scope", you can use angular.extend to shallow copy the scope's properties to another object, and then bind the object to your view:

Directive

   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>

Upvotes: 1

Related Questions