Angular.js: Difference between revisions

From Adam Colton
Jump to navigation Jump to search
Line 98: Line 98:


== What I don't Get ==
== What I don't Get ==
It seems that the tight coupling of logic and display is bad.
It seems that the tight coupling of logic and display is bad. Particularly embedding a turing-complete DSL in element attributes.


Binding is a neat trick, but is it really useful? Often I don't want the display tightly coupled to the model so that I can perform some layer of processing on it.
Binding is a neat trick, but is it really useful? Often I don't want the display tightly coupled to the model so that I can perform some layer of processing on it.

Revision as of 13:15, 11 August 2014

Creating an App

 var app = angular.module('appName', []); // the [] is for dependencies

Then, in the html

 ng-app="app"

Creating a controller

 function ControllerName($scope, ...services) {
   $scope.something = data;
 
   $scope.method = function(stuff){
     return otherStuff;
   };
 }

or

 app.controller("name", function(){});

An easier way

 var controllers = {
   controller1: function(){},
   controller2: function(){}
 }
 app.controller(controllers);

This works for directives too, but not filters.

Service

 app.factory('ServiceName', function(){
   return serviceData;
 })

Filter

app.filter('filterName', function(){

 return function(intput){
   ...stuff...goes...here...
 };

})

Filters are applied with |

Built in array filters

  • filter:string
  • orderby:attr
  • first:n

Built in test filters

  • uppercase
  • lowercase

Directives

 app.directive("name", function(){
   return {
     restrict: "E",
     requires: "someDirective",
     scope: {}, //or something else
     template: "some html",
     link: function(scope, element, attrs) {
       modify element
     }
   };
 })

restrict:

  • A: attribute, this is the default
  • E: element
  • C: class
  • M: comment () not used much

or, the short form for A

 app.directive("name", function(){
   return function(scope, element, attrs, controller){
     //now have access to element and scope
     //we have access to our attr via attrs.name
     //if the attr is a function, scope.$apply(attrs.name)
   }
 })

Isolate

 scoope: {
   val: "@"
 }
  • @: attrs.name, gets the string value of the attribute
  • =: gets the object value
  • &: parent scope, or..., method on parent scope, maybe?

Difference in Types

 module.service( 'serviceName', funcFooBar );

When injected, will return new funcFooBar()

 module.factory( 'factoryName', funcFooBar );

When inject, will return the result of funcFooBar().

I still don't understand providers.

What I don't Get

It seems that the tight coupling of logic and display is bad. Particularly embedding a turing-complete DSL in element attributes.

Binding is a neat trick, but is it really useful? Often I don't want the display tightly coupled to the model so that I can perform some layer of processing on it.