1

We are always told to ensure proper separation of concerns (How do I “think in AngularJS” if I have a jQuery background?), and that the view should be the official record of what is going on.

Suppose we have a directive that dynamically the src of an element based on a separate function. I was under the impression that we should pass in a function to the directive using an isolate scope and '&'.

However, does this count as not separating concerns since the view now contains logic? Or is it okay because myFunction() is stored in the controller?

<img my-src callback='myFunction()' />

HTML

<body ng-app='testApp'>
    <div ng-controller='TestCtrl'>
        <img my-src callback='myFunction()' />
    </div>
</body>

JS

angular.module('testApp', [])
.controller('TestCtrl', function($scope) {
    $scope.myFunction = function() {
        return 'http://nodejs.org/images/roadshow-promo.png';
    }
})
.directive('mySrc', function() {
    return {
        restrict: 'A',
        scope: {
            callback: '&'
        },
        link: function ( scope, elem, attrs ) {
            elem.attr('src', scope.callback());
        }
    };
})
Community
  • 1
  • 1
Dan Tang
  • 1,273
  • 2
  • 20
  • 35

1 Answers1

0

To me this looks fine, the controller is still in control what the view shows... But if it's really only setting the src dynamically, you could use ng-src.

<img ng-src="{{ myFunction() }}" />

Example here: http://plnkr.co/edit/Rw2OG1ltrmpUO2oLO1fE?p=preview

philippd
  • 606
  • 5
  • 6