Access factory from directive

####Objective####

  1. Example of showing directive accesses service (factory).
  2. Example of ng-src

<!-- more --> <iframe style="margin:20px 0; width: 100%; height: 300px" src="http://embed.plnkr.co/qGAvEtXmkJ3opTRvZUMQ" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

MarkupGithub
1
2
3
4
5
Avatar url : <input type="text" ng-model="url" placeholder='input url'/>
<div> result:
<img my-avatar/>
</div>
AngularJSGithub
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var app = angular.module('myApp', [])
.factory('CurrentUserService', function () {
"use strict";
var user = {
avatarUrl: ''
}, srv = {};
srv.getCurrentUser = function () {
return user;
};
return srv;
}).directive('myAvatar', function () {
"use strict";
return {
restrict: 'A',
replace: true,
template: '<img class="avatar" ng-src="" alt="" title=""> ',
controller: function ($scope, CurrentUserService) {
$scope.url = CurrentUserService.getCurrentUser().avatarUrl;
}
};
});
app.controller('MainCtrl', ['$scope', 'CurrentUserService', function ($scope, CurrentUserService) {
"use strict";
CurrentUserService.getCurrentUser().avatarUrl = $scope.url;
}]);