Last active
January 4, 2016 21:39
-
-
Save trivektor/8682109 to your computer and use it in GitHub Desktop.
Different ways/syntaxes to do things in AngularJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inject a service into a controller (source: http://stackoverflow.com/a/14418384/477697) | |
function MyCtrl($scope, $injector) { | |
$scope.doSomething = function(someService) { | |
var service = $injector.get(someService) // someService contains the name of a service | |
service.value += 10 | |
} | |
// Define a service (source: http://stackoverflow.com/a/15904939/477697) | |
function MyObjectWithParam($rootScope, name) { | |
this.$rootScope = $rootScope; | |
this.name = name; | |
} | |
MyObjectWithParam.prototype.getText = function () { | |
return this.name; | |
}; | |
App.factory('MyObjectWithParam', function ($injector) { | |
return function(name) { | |
return $injector.instantiate(MyObjectWithParam,{ name: name }); | |
}; | |
}); | |
// Prototypal inheritance with controllers (source: http://blog.mgechev.com/2013/12/18/inheritance-services-controllers-in-angularjs/) | |
function BaseCtrl($scope, $location, ...) { | |
$scope.commonScopeMethod = function () { | |
//body | |
}; | |
$scope.commonVar = 42; | |
} | |
BaseCtrl.prototype.commonMethod1 = function () { | |
//body | |
}; | |
BaseCtrl.prototype.commonMethod2 = function () { | |
//body | |
}; | |
function ChildCtrl1($scope, $location, ...) { | |
BaseCtrl.call(this, $scope, $location, ...); | |
$scope.childScopeMethod = function () { | |
}; | |
} | |
ChildCtrl1.prototype = Object.create(BaseCtrl.prototype); | |
ChildCtrl1.prototype.childMethod1 = function () { | |
this.commonMethod1(); | |
}; | |
myModule.controller('ChildCtrl1', ChildCtrl1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment