aboutsummaryrefslogtreecommitdiffstats
path: root/src/ng/rootElement.js
diff options
context:
space:
mode:
authorIgor Minar2013-01-23 10:54:35 -0800
committerIgor Minar2013-01-23 10:54:35 -0800
commit574573499128f18dabc29dbd2cbd54a59f5a4f0e (patch)
treec81f8cb271b01f0364ef042aaa7f8bdfd91c35e6 /src/ng/rootElement.js
parent0551aa95f0376c52568a027296e225d828cede38 (diff)
downloadangular.js-574573499128f18dabc29dbd2cbd54a59f5a4f0e.tar.bz2
chore(release): cut 1.1.2 tofu-animation releasev1.1.2
Diffstat (limited to 'src/ng/rootElement.js')
0 files changed, 0 insertions, 0 deletions
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
'use strict';

/**
 * @ngdoc function
 * @name angular.directive
 * @description
 *
 * Angular directives create custom attributes for DOM elements. A directive can modify the
 * behavior of the element in which it is specified. Do not use directives to add elements to the
 * DOM; instead, use {@link angular.widget widgets} to add DOM elements.
 *
 * For more information about how Angular directives work, and to learn how to create your own
 * directives, see {@link guide/dev_guide.compiler.directives Understanding Angular Directives} in
 * the Angular Developer Guide.
 *
 * @param {string} name Directive identifier (case insensitive).
 * @param {function(string, Element)} compileFn Also called "template function" is a function called
 *    during compilation of the template when the compiler comes across the directive being
 *    registered. The string value of the element attribute representing the directive and
 *    jQuery/jqLite wrapped DOM element are passed as arguments to this function.
 *
 *    The `compileFn` function may return a linking function also called an instance function.
 *    This function is called during the linking phase when a Scope is being associated with the
 *    template or template clone (see repeater notes below). The signature of the linking function
 *    is: `function(Element)` where Element is jQuery/jqLite wrapped DOM Element that is being
 *    linked.
 *
 * The biggest differenciator between the compile and linking functions is how they are being called
 * when a directive is present within an {@link angular.widget.@ng:repeat ng:repeat}. In this case,
 * the compile function gets called once per occurence of the directive in the template. On the
 * other hand the linking function gets called once for each repeated clone of the template (times
 * number of occurences of the directive in the repeated template).
 */

/**
 * @ngdoc directive
 * @name angular.directive.ng:init
 *
 * @description
 * The `ng:init` attribute specifies initialization tasks to be executed
 *  before the template enters execution mode during bootstrap.
 *
 * @element ANY
 * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval.
 *
 * @example
   <doc:example>
     <doc:source>
    <div ng:init="greeting='Hello'; person='World'">
      {{greeting}} {{person}}!
    </div>
     </doc:source>
     <doc:scenario>
       it('should check greeting', function() {
         expect(binding('greeting')).toBe('Hello');
         expect(binding('person')).toBe('World');
       });
     </doc:scenario>
   </doc:example>
 */
angularDirective("ng:init", function(expression){
  return function(element){
    this.$eval(expression);
  };
});

/**
 * @ngdoc directive
 * @name angular.directive.ng:controller
 *
 * @description
 * The `ng:controller` directive assigns behavior to a scope. This is a key aspect of how angular
 * supports the principles behind the Model-View-Controller design pattern.
 *
 * MVC components in angular:
 *
 * * Model — The Model is data in scope properties; scopes are attached to the DOM.
 * * View — The template (HTML with data bindings) is rendered into the View.
 * * Controller — The `ng:controller` directive specifies a Controller class; the class has
 *   methods that typically express the business logic behind the application.
 *
 * Note that an alternative way to define controllers is via the `{@link angular.module.ng.$route}`
 * service.
 *
 * @element ANY
 * @param {expression} expression Name of a globally accessible constructor function or an
 *     {@link guide/dev_guide.expressions expression} that on the current scope evaluates to a
 *     constructor function.
 *
 * @example
 * Here is a simple form for editing user contact information. Adding, removing, clearing, and
 * greeting are methods declared on the controller (see source tab). These methods can
 * easily be called from the angular markup. Notice that the scope becomes the `this` for the
 * controller's instance. This allows for easy access to the view data from the controller. Also
 * notice that any changes to the data are automatically reflected in the View without the need
 * for a manual update.
   <doc:example>
     <doc:source>
      <script type="text/javascript">
        function SettingsController($scope) {
          $scope.name = "John Smith";
          $scope.contacts = [
            {type:'phone', value:'408 555 1212'},
            {type:'email', value:'john.smith@example.org'} ];

          $scope.greet = function() {
           alert(this.name);
          };

          $scope.addContact = function() {
           this.contacts.push({type:'email', value:'yourname@example.org'});
          };

          $scope.removeContact = function(contactToRemove) {
           var index = this.contacts.indexOf(contactToRemove);
           this.contacts.splice(index, 1);
          };

          $scope.clearContact = function(contact) {
           contact.type = 'phone';
           contact.value = '';
          };
        }
      </script>
      <div ng:controller="SettingsController">
        Name: <input type="text" ng:model="name"/>
        [ <a href="" ng:click="greet()">greet</a> ]<br/>
        Contact:
        <ul>
          <li ng:repeat="contact in contacts">
            <select ng:model="contact.type">
               <option>phone</option>
               <option>email</option>
            </select>
            <input type="text" ng:model="contact.value"/>
            [ <a href="" ng:click="clearContact(contact)">clear</a>
            | <a href="" ng:click="removeContact(contact)">X</a> ]
          </li>
          <li>[ <a href="" ng:click="addContact()">add</a> ]</li>
       </ul>
      </div>
     </doc:source>
     <doc:scenario>
       it('should check controller', function() {
         expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
         expect(element('.doc-example-live li:nth-child(1) input').val())
           .toBe('408 555 1212');
         expect(element('.doc-example-live li:nth-child(2) input').val())
           .toBe('john.smith@example.org');

         element('.doc-example-live li:first a:contains("clear")').click();
         expect(element('.doc-example-live li:first input').val()).toBe('');

         element('.doc-example-live li:last a:contains("add")').click();
         expect(element('.doc-example-live li:nth-child(3) input').val())
           .toBe('yourname@example.org');
       });
     </doc:scenario>
   </doc:example>
 */
angularDirective("ng:controller", function(expression) {
  this.scope(true);
  return ['$controller', '$window', function($controller, $window) {
    var scope = this,
        Controller = getter(scope, expression, true) || getter($window, expression, true);

    assertArgFn(Controller, expression);
    $controller(Controller, scope);
  }];
});

/**
 * @ngdoc directive
 * @name angular.directive.ng:bind
 *
 * @description
 * The `ng:bind` attribute tells Angular to replace the text content of the specified HTML element
 * with the value of a given expression, and to update the text content when the value of that
 * expression changes.
 *
 * Typically, you don't use `ng:bind` directly, but instead you use the double curly markup like
 * `{{ expression }}` and let the Angular compiler transform it to
 * `<span ng:bind="expression"></span>` when the template is compiled.
 *
 * @element ANY
 * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate.
 *
 * @example
 * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
   <doc:example>
     <doc:source>
       <script>
         function Ctrl($scope) {
           $scope.name = 'Whirled';
         }
       </script>
       <div ng:controller="Ctrl">
         Enter name: <input type="text" ng:model="name"> <br/>
         Hello <span ng:bind="name"></span>!
       </div>
     </doc:source>
     <doc:scenario>
       it('should check ng:bind', function() {
         expect(using('.doc-example-live').binding('name')).toBe('Whirled');
         using('.doc-example-live').input('name').enter('world');
         expect(using('.doc-example-live').binding('name')).toBe('world');
       });
     </doc:scenario>
   </doc:example>
 */
angularDirective("ng:bind", function(expression, element){
  element.addClass('ng-binding');
  return ['$exceptionHandler', '$parse', '$element', function($exceptionHandler, $parse, element) {
    var exprFn = $parse(expression),
        lastValue = Number.NaN,
        scope = this;

    scope.$watch(function() {
      // TODO(misko): remove error handling https://github.com/angular/angular.js/issues/347
      var value, html, isHtml, isDomElement,
          hadOwnElement = scope.hasOwnProperty('$element'),
          oldElement = scope.$element;
      // TODO(misko): get rid of $element https://github.com/angular/angular.js/issues/348
      scope.$element = element;
      try {
        value = exprFn(scope);
        // If we are HTML than save the raw HTML data so that we don't recompute sanitization since
        // it is expensive.
        // TODO(misko): turn this into a more generic way to compute this
        if ((isHtml = (value instanceof HTML)))
          value = (html = value).html;
        if (lastValue === value) return;
        isDomElement = isElement(value);
        if (!isHtml && !isDomElement && isObject(value)) {
          value = toJson(value, true);
        }
        if (value != lastValue) {
          lastValue = value;
          if (isHtml) {
            element.html(html.get());
          } else if (isDomElement) {
            element.html('');
            element.append(value);
          } else {
            element.text(value == undefined ? '' : value);
          }
        }
      } catch (e) {
        $exceptionHandler(e);
      } finally {
        if (hadOwnElement) {
          scope.$element = oldElement;
        } else {
          delete scope.$element;
        }
      }
    });
  }];
});


/**
 * @ngdoc directive
 * @name angular.directive.ng:bind-template
 *
 * @description
 * The `ng:bind-template` attribute specifies that the element
 * text should be replaced with the template in ng:bind-template.
 * Unlike ng:bind the ng:bind-template can contain multiple `{{` `}}`
 * expressions. (This is required since some HTML elements
 * can not have SPAN elements such as TITLE, or OPTION to name a few.)
 *
 * @element ANY
 * @param {string} template of form
 *   <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
 *
 * @example
 * Try it here: enter text in text box and watch the greeting change.
   <doc:example>
     <doc:source>
       <script>
         function Ctrl($scope) {
           $scope.salutation = 'Hello';
           $scope.name = 'World';
         }
       </script>
       <div ng:controller="Ctrl">
        Salutation: <input type="text" ng:model="salutation"><br/>
        Name: <input type="text" ng:model="name"><br/>
        <pre ng:bind-template="{{salutation}} {{name}}!"></pre>
       </div>
     </doc:source>
     <doc:scenario>
       it('should check ng:bind', function() {
         expect(using('.doc-example-live').binding('{{salutation}} {{name}}')).
           toBe('Hello World!');
         using('.doc-example-live').input('salutation').enter('Greetings');
         using('.doc-example-live').input('name').enter('user');
         expect(using('.doc-example-live').binding('{{salutation}} {{name}}')).
           toBe('Greetings user!');
       });
     </doc:scenario>
   </doc:example>
 */
angularDirective("ng:bind-template", function(expression, element){
  element.addClass('ng-binding');
  var templateFn = compileBindTemplate(expression);
  return function(element) {
    var lastValue,
        scope = this;

    scope.$watch(function() {
      var value = templateFn(scope, element, true);
      if (value != lastValue) {
        element.text(value);
        lastValue = value;
      }
    });
  };
});

/**
 * @ngdoc directive
 * @name angular.directive.ng:bind-attr
 *
 * @description
 * The `ng:bind-attr` attribute specifies that a
 * {@link guide/dev_guide.templates.databinding databinding}  should be created between a particular
 * element attribute and a given expression. Unlike `ng:bind`, the `ng:bind-attr` contains one or
 * more JSON key value pairs; each pair specifies an attribute and the
 * {@link guide/dev_guide.expressions expression} to which it will be mapped.
 *
 * Instead of writing `ng:bind-attr` statements in your HTML, you can use double-curly markup to
 * specify an <tt ng:non-bindable>{{expression}}</tt> for the value of an attribute.
 * At compile time, the attribute is translated into an
 * `<span ng:bind-attr="{attr:expression}"></span>`.
 *
 * The following HTML snippet shows how to specify `ng:bind-attr`:
 * <pre>
 *   <a ng:bind-attr='{"href":"http://www.google.com/search?q={{query}}"}'>Google</a>
 * </pre>
 *
 * This is cumbersome, so as we mentioned using double-curly markup is a prefered way of creating
 * this binding:
 * <pre>
 *   <a href="http://www.google.com/search?q={{query}}">Google</a>
 * </pre>
 *
 * During compilation, the template with attribute markup gets translated to the ng:bind-attr form
 * mentioned above.
 *
 * _Note_: You might want to consider using {@link angular.directive.ng:href ng:href} instead of
 * `href` if the binding is present in the main application template (`index.html`) and you want to
 * make sure that a user is not capable of clicking on raw/uncompiled link.
 *
 *
 * @element ANY
 * @param {string} attribute_json one or more JSON key-value pairs representing
 *    the attributes to replace with expressions. Each key matches an attribute
 *    which needs to be replaced. Each value is a text template of
 *    the attribute with the embedded
 *    <tt ng:non-bindable>{{expression}}</tt>s. Any number of
 *    key-value pairs can be specified.
 *
 * @example
 * Enter a search string in the Live Preview text box and then click "Google". The search executes instantly.
   <doc:example>
     <doc:source>
       <script>
         function Ctrl($scope) {
           $scope.query = 'AngularJS';
         }
       </script>
       <div ng:controller="Ctrl">
        Google for:
        <input type="text" ng:model="query"/>
        <a ng:bind-attr='{"href":"http://www.google.com/search?q={{query}}"}'>
          Google
        </a> (ng:bind-attr) |
        <a href="http://www.google.com/search?q={{query}}">Google</a>
        (curly binding in attribute val)
       </div>
     </doc:source>
     <doc:scenario>
       it('should check ng:bind-attr', function() {
         expect(using('.doc-example-live').element('a').attr('href')).
           toBe('http://www.google.com/search?q=AngularJS');
         using('.doc-example-live').input('query').enter('google');
         expect(using('.doc-example-live').element('a').attr('href')).
           toBe('http://www.google.com/search?q=google');
       });
     </doc:scenario>
   </doc:example>
 */
angularDirective("ng:bind-attr", function(expression){
  return function(element){
    var lastValue = {},
        scope = this;

    scope.$watch(function() {
      var values = scope.$eval(expression);
      for(var key in values) {
        var value = compileBindTemplate(values[key])(scope, element);
        if (lastValue[key] !== value) {
          lastValue[key] = value;
          element.attr(key, BOOLEAN_ATTR[lowercase(key)] ? toBoolean(value) : value);
        }
      }
    });
  };
});


/**
 * @ngdoc directive
 * @name angular.directive.ng:click
 *
 * @description
 * The ng:click allows you to specify custom behavior when
 * element is clicked.
 *
 * @element ANY
 * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon
 * click.
 *
 * @example
   <doc:example>
     <doc:source>
      <button ng:click="count = count + 1" ng:init="count=0">
        Increment
      </button>
      count: {{count}}
     </doc:source>
     <doc:scenario>
       it('should check ng:click', function() {
         expect(binding('count')).toBe('0');
         element('.doc-example-live :button').click();
         expect(binding('count')).toBe('1');
       });
     </doc:scenario>
   </doc:example>
 */
/*
 * A directive that allows creation of custom onclick handlers that are defined as angular
 * expressions and are compiled and executed within the current scope.
 *
 * Events that are handled via these handler are always configured not to propagate further.
 *
 * TODO: maybe we should consider allowing users to control event propagation in the future.
 */
angularDirective("ng:click", function(expression, element){
  return function(element){
    var self = this;
    element.bind('click', function(event){
      self.$apply(expression);
      event.stopPropagation();
    });
  };
});


/**
 * @ngdoc directive
 * @name angular.directive.ng:submit
 *
 * @description
 * Enables binding angular expressions to onsubmit events.
 *
 * Additionally it prevents the default action (which for form means sending the request to the
 * server and reloading the current page).
 *
 * @element form
 * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval.
 *
 * @example
   <doc:example>
     <doc:source>
      <script>
        function Ctrl($scope) {
          $scope.list = [];
          $scope.text = 'hello';
          $scope.submit = function() {
            if (this.text) {
              this.list.push(this.text);
              this.text = '';
            }
          };
        }
      </script>
      <form ng:submit="submit()" ng:controller="Ctrl">
        Enter text and hit enter:
        <input type="text" ng:model="text" name="text" />
        <input type="submit" id="submit" value="Submit" />
        <pre>list={{list}}</pre>
      </form>
     </doc:source>
     <doc:scenario>
       it('should check ng:submit', function() {
         expect(binding('list')).toBe('list=[]');
         element('.doc-example-live #submit').click();
         expect(binding('list')).toBe('list=["hello"]');
         expect(input('text').val()).toBe('');
       });
       it('should ignore empty strings', function() {
         expect(binding('list')).toBe('list=[]');
         element('.doc-example-live #submit').click();
         element('.doc-example-live #submit').click();
         expect(binding('list')).toBe('list=["hello"]');
       });
     </doc:scenario>
   </doc:example>
 */
angularDirective("ng:submit", function(expression, element) {
  return function(element) {
    var self = this;
    element.bind('submit', function() {
      self.$apply(expression);
    });
  };
});


function ngClass(selector) {
  return function(expression, element) {
    return function(element) {
      var scope = this;
      scope.$watch(expression, function(newVal, oldVal) {
        if (selector(scope.$index)) {
          if (oldVal && (newVal !== oldVal)) {
            if (isObject(oldVal) && !isArray(oldVal))
              oldVal = map(oldVal, function(v, k) { if (v) return k });
            element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal);
          }
          if (isObject(newVal) && !isArray(newVal))
            newVal = map(newVal, function(v, k) { if (v) return k });
          if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal);
        }
      });
    };
  };
}

/**