
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name">
<hr>
<h1>Hello !</h1>
Hello {{yourName}}!
// Get the scope of an inspected elementangular.element($0).scope();
function MyCtrl($scope) { $scope.yourName2 = '<Please type a name>'; $scope.resetName = function () { $scope.yourName2 = '<Please type a name>'; } }// Input and Button HTML: <input ng-model="yourName2" placeholder="Enter a name"><button ng-click="resetName()">Reset</button>
My Name is {{yourName2}}
function MyCtrl($scope) { $scope.$watch('myName', function(newVal) {$scope.characterLength = newVal.length;}); }
That's {{characterLength}} characters
$apply() is used to execute an expression in angular from outside of the angular framework.
Sample external execution contexts:
function MyCtrl() { $scope.startTimeout1 = function () { setTimeout(function () { $scope.message1 = "Timeout 1 called!"; }, 5000); } $scope.startTimeout2 = function () { setTimeout(function () { $scope.$apply(function () { $scope.message2 = "Timeout 2 called!"; }); }, 5000); } }
Directives are a way to teach HTML new tricks
Ways to invoke a directive
// Attribute<span my-dir="exp"></span>// Class<span class="my-dir: exp;"></span>// Element<my-dir></my-dir>// Comment<!-- directive: my-dir exp -->
<geo-* > <il8n-* >
<dc-* > <mj-* > <bm-* >
Dependency Injection (DI) is a software design pattern that deals with how code gets hold of its dependencies.
angular.module('myModule', []). factory('greeter', function($window) { return { greet: function(text) { $window.alert(text); } }; });// Inferring Dependenciesfunction MyController($scope, greeter) {... }
// $indect Annotationvar MyController = function(renamed$scope, renamedGreeter) { ... } MyController.$inject = ['$scope', 'greeter'];
// Inline Annotationangular.module('myModule', []). factory('greeter', ['srv1', 'srv2',... function(srv1, s2,...) {... });
The most common way to keep controllers slim is by encapsulating work that doesn't belong to controllers into services and then using these services in controllers via dependency injection.