📜 ⬆️ ⬇️

Easy controllers with Angular Classy

Found a curious tool to facilitate the structure of controllers - Angular Classy . It is a module, 1 kilobyte in size (gzipped and minified), and in addition to representing the controller as an object, it gives a number of useful buns, a story about which is under the cut.





Structure


As the application grows, controllers tend to grow to such an extent that once it becomes quite difficult to navigate among them. Classy uses a class-based approach and inherits some ideas from AngularDart to make the code cleaner and more structured.
')


No need to describe dependencies in detail


Those who tried to minify the Angular-code know that the annotation of dependencies is necessary for its correct operation. Native code with repetitions looks like this:

app.controller('AppCtrl', ['$scope', '$location', '$http', function($scope, $location, $http) { // ... }]); 

In addition to the fact that this kind of annotation is boring, it doesn’t look like something very ... With Classy, ​​everything is different:

 app.classy.controller({ name: 'AppCtrl', inject: ['$scope', '$location', '$http'], //... }); 



Convenient $ scope


In most cases, when we create a function in the controller, it is important for us that it is available in $ scope, for example, to have access to it from the template. Be aware: all object functions will be automatically added to $ scope. In other words, the native code without Classy looks like this:

 $scope.editTodo = function(todo) { //... } 

With Classy looks like this:

 editTodo: function(todo) { //... } 

And if you don’t want this or that function to be added to $ scope, just use the “_” character as a prefix in its name.

Meek record $ scope


To access the $ scope properties, you can simply access this.$.foo = 'bar'; instead of this.$scope.foo = 'bar'; . At the same time using this.$scope also not forbidden.



Special object for $ watch listeners


Instead of littering the init method with a bunch of $scope.$watch , Classy calls to add them to a special object:

 watch: { 'location.path()': function(newValue, oldValue) { // ... }, '{object}todos': function (newValue, oldValue) { // ... } } 

Note the {object} in the name of the second listener. This entry allows you to specify the type of listener. Thus, the presence of {collection} or {shallow} will indicate that $watchCollection() should be applied to the object. A full list of possible values ​​can be found on the Classy website



And that's not all the amenities that Classy has!
Interested please read .

Source: https://habr.com/ru/post/221903/


All Articles