removed outdated angular info

This commit is contained in:
Bernhard Posselt
2013-03-13 11:33:56 +01:00
parent 1bab9c22cb
commit 2006e45afd
3 changed files with 8 additions and 383 deletions

View File

@@ -1,4 +1,6 @@
JavaScript
==========
AngularJS
=========
.. sectionauthor:: Bernhard Posselt <nukeawhale@gmail.com>
.. sectionauthor:: Bernhard Posselt <nukeawhale@gmail.com>
The App Framework comes with tools for integrating :doc:`../general/angular` into the app.

View File

@@ -114,382 +114,6 @@ When porting the News app to AngularJS we found that the benefits outweighed the
But all in all you should build an optimized prototype and compare it to a non angular app to make sure that the user experience is good.
Using AngularJS in your project
-------------------------------
Since you'll have lots of files, a buildscript is recommended to merge the JavaScript into a single file. For that `CoffeeScript <http://coffeescript.org/>`_ and a `Cakefile <http://k20e.com/blog/2011/05/02/a-piece-of-cakefile/>`_ is recommended.
You can install CoffeeScript via NPM (nodejs package manager)::
sudo npm -g install coffee-script
Place the Cakefile in your app directory. When executing::
cake watch
the Cakefile will automatically watch the coffee folder for changes and compile the files when it finds a change.
The following folderstructure is recommended::
coffee/
coffee/directives/
coffee/filters/
coffee/controllers/
coffee/services/
For a simple example, take a look at the `apptemplateadvanced <https://github.com/owncloud/apps/tree/master/apptemplateadvanced>`_ app.
Create your app
---------------
.. note:: For the sake of syntax highlightning, this tutorial will use JavaScript instead of CoffeeScript
Your app initialization will be in::
coffee/app.coffee
and will look like this:
.. code-block:: javascript
angular.module('YourApp', []).
config(['$provide', function($provide){
// Use this for configuration values
var Config = {
// your config values here
};
// declare your routes here
Config.routes = {
saveNameRoute: 'apptemplate_advanced_ajax_setsystemvalue'
};
return $provide.value('Config', Config);
}
]);
.. note:: It is important that this file is at the beginning of the compiled JavaScript! The square brackets [] create a new app. If you only use **angular.module('YourApp')** it will retrieve the app instance.
You will want to also add the run function to the same file to do some initial setup. The run function is run once angular is set up. That doesnt mean though that the document is ready
.. code-block:: javascript
angular.module('YourApp').
run(['$rootScope', function($rootScope){
var init = function(){
$rootScope.$broadcast('routesLoaded');
};
// this registers a callback that is executed once the routes have
// finished loading. Before this you cant really do request
OC.Router.registerLoadedCallback(init);
}
]);
The next move is to add the **ng-app="YourApp"** attribute to the root element of your application. Everything inside of it will be processed by Angular.
Controllers
-----------
Controllers are the mediators between your view and your data. Assign controllers to different parts of your page. **Don't nest controllers!** Every controller should have one specific area of your page.
A controller could look like this:
.. code-block:: javascript
angular.module('YourApp').
factory('ExampleController', ['$scope', 'Config', 'Request',
function($scope, Config, Request){
var Controller = function($scope, Config, Request){
var self = this;
this.$scope = $scope;
this.config = Config;
this.request = Request;
// bind methods on the scope so that you can access them in the
// controllers child HTML
this.$scope.saveName = function(name){
self.saveName(name);
};
};
/**
* Makes an ajax query to save the name
*/
Controller.prototype.saveName = function(name){
this.request.saveName(this.config.routes.saveNameRoute, name);
};
return new Controller($scope, Config, Request);
}
]);
To each controller a **$scope** object is passed. The scope is the glue between the view and the controller.
.. note:: because controllers use the $scope object to connect to the view, you shouldn't pass in references of DOM elements. Use directives if you need to bind behaviour to DOM elements.
Inside the square brackets (['$scope', 'Config', 'Request', function ...), you define the dependencies that need to be passed in to the object. This is the how Dependency Injection works in Angular.
A controller is bound to an HTML element with the **ng-controller** attribute. Everything on that element or below it will be in the controller's scope:
.. code-block:: html
<ul ng-controller="ExampleController">
<li ng-click="saveName('john')"></li>
</ul>
Models & Services
-----------------
Models hold your data. There isn't a specific implementation for models in Angular but it's useful to put the data into own objects. Inside these objects you can create hashmaps for quick access by ID or simply add new functionality or properties to the data.
This is a little example how you could encapsulate data for a Button Model. Most of the functionality should go into a generic parent object though, once you use more than one model.
.. code-block:: javascript
angular.module('YourApp').
factory('ButtonModel', function(){
var ButtonModel = function(){
this.buttons = [];
this.buttonHashMap = {};
};
ButtonModel.prototype.add = function(button){
this.buttons.add(button);
this.buttonHashMap[button.id] = button;
};
ButtonModel.prototype.getById = function(buttonId){
return this.buttonHashMap[buttonId];
};
ButtonModel.prototype.getItems = function(){
return this.buttons;
};
return new ButtonModel();
}
]);
A service can be seen as a single instance of an item. You can use it to share data between controllers for instance. A model is a service, but you could create an even simpler service which contains only an object:
.. code-block:: javascript
angular.module('YourApp').
factory('ActiveFeed', function(){
return {
id: 5
};
}
]);
Filters
-------
Filters are used to transform objects or strings before you render them. They are basically just a function that receive an input and returns a result.
Built-In filters contain functions like **orderBy** (orders array of objects by a specific attribute) or **uppercase** (turns string to uppercase).
.. note:: Due to performance reasons you shouldn't use filters to return objects by a certain foreign key. Remember: everytime an element is updated, everything is sent through the filter again (O(n) algorithmic complexity)
A simple filter would look like this:
.. code-block:: javascript
angular.module('YourApp').
filter('biggerThanX', function(){
var biggerThanX = function(elements, x){
result = [];
for(var i=0; i<elements.length; i++){
var elem = elements[i];
if(elem.someNumber > x){
results.push(elem);
}
}
return result;
};
return biggerThanX;
}
);
]);
Filters are used like Unix Pipes in the Bash:
.. code-block:: html
<ul ng-controller="SomeController">
<li ng-repeat="item in items | biggerThanX:5">{{ item.someNumber }}</li>
</ul>
Directives
----------
Directives are powerful yet complex for beginners. You can create your own XML elements or XML attributes, or simply map eventlisteners to HTML elements.
Everytime you are in need to do something directly to a DOM element, you should write a directive for it.
This is an example that uses a directive to bind jQuery draggable and dropable to a DOM element:
.. code-block:: javascript
angular.module('YourApp').directive('draggable', function(){
return function(scope, elm, attr){
var details = {
revert: true,
stack: '> li',
zIndex: 1000,
axis: 'y',
};
$(elm).draggable(details);
};
});
angular.module('YourApp').directive('droppable', function(){
return function(scope, elm, attr){
var details = {
greedy: true,
drop: function(event, ui){
console.log('this was dropped on me');
console.log(ui.draggable);
scope.$apply(attr.droppable);
}
};
$(elm).droppable(details);
};
});
It can now be applied to any element by simply adding an attribute:
.. code-block:: html
<li draggable>nothing to see here</li>
<ul droppable></ul>
Since a directive is a new element outside of the current Angular Framework, we have to trigger a view update by using the **scope.$apply** function.
This is only a `fraction of directive applications <http://www.youtube.com/watch?v=A6wq16Ow5Ec>`_ though.
Requests
--------
For simple post or get requests, Angular offers the **$http** object. It's very helpful to encapsulate it into an own object though. You will want to use the object to implicitely send the CSRF token to the server.
.. code-block:: javascript
angular.module('YourApp').
factory('Request', ['$http', '$rootScope', 'Config', function($http, $rootScope, Config){
var Request = function($http, $rootScope, Config){
var self = this;
this.$http = $http;
this.$rootScope = $rootScope;
this.config = Config;
// if the routes are not yet initialized we dont want to lose
// requests. Save all requests and run them when the routes are
// ready
this.initialized = false;
this.shelvedRequests = [];
this.$rootScope.$on('routesLoaded', function(){
for(var i=0; i<self.shelvedRequests.length; i++){
var req = self.shelvedRequests[i];
self.post(req.route, req.routeParams, req.data,
req.onSuccess, req.onFailure);
}
self.initialized = true;
self.shelvedRequests = [];
});
};
/**
* Do the actual post request
* @param string route: the url which we want to request
* @param object routeParams: Parameters that are needed to generate
* the route
* @param object data: the post params that we want to pass
* @param function onSuccess: the function that will be called if
* the request was successful
* @param function onFailure: the function that will be called if the
* request failed
*/
Request.prototype.post = function(route, routeParams, data, onSuccess, onFailure){
// if routes are not ready yet, save the request
if(!this.initialized){
var request = {
route: route,
routeParams: routeParams,
data: data,
onSuccess: onSuccess,
onFailure: onFailure
};
this.shelvedRequests.push(request);
return;
}
var url;
if(routeParams){
url = OC.Router.generate(route, routeParams);
} else {
url = OC.Router.generate(route);
}
// encode data object for post
var postData = data || {};
postData = $.param(data);
// pass the CSRF token as header
var headers = {
requesttoken: oc_requesttoken,
'Content-Type': 'application/x-www-form-urlencoded'
};
// do the actual request
this.$http.post(url, postData, {headers: headers}).
success(function(data, status, headers, config){
if(onSuccess){
onSuccess(data);
}
}).
error(function(data, status, headers, config){
if(onFailure){
onFailure(data);
}
});
};
]);
Closing remarks
---------------
This was a minimal fraction of Angular but it should give you a good idea about how Angular works (If not, please help to improve the documentation ;) ). More directives and objects are available on the `official API Page <http://docs.angularjs.org/api/>`_

View File

@@ -53,7 +53,7 @@ ownCloud has to know what your app is. This information is located inside the :f
<require>6</require>
</info>
For more information on the content of :file:`appinfo/info.xml` and what can be set, see: :doc:`../app/info`
For more information on the content of :file:`appinfo/info.xml` see: :doc:`../app/info`
Enable the app
--------------
@@ -94,11 +94,10 @@ To simplify the decision see this comparison chart:
| Templates | :php:class:`OC_Template`| :php:class:`OC_Template` |
| | | and `Twig`_ |
+-----------------+-------------------------+--------------------------------+
| Security | manual checks | enforces XSS, CSRF and |
| | | Authentication checks by |
| Security | manual checks | enforces XSS (Twig only), CSRF |
| | | and Authentication checks by |
| | | default |
+-----------------+-------------------------+--------------------------------+
.. _Twig: http://twig.sensiolabs.org
.. _TDD: http://en.wikipedia.org/wiki/Test-driven_development
.. _Dependency Injection: