简体   繁体   中英

Separation of concerns in angular - passing functions to directives

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());
        }
    };
})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM