1
我们经常被告知确保正确分离关注点(How do I “think in AngularJS” if I have a jQuery background?),并且该视图应该是正在进行的正式记录。将角度传递函数中的顾虑分离为指令
假设我们有一个动态的基于单独函数的元素的src指令。我的印象是,我们应该使用隔离范围和'&'将函数传递给指令。
但是,这是否算作不分离的问题,因为现在视图包含逻辑?还是没关系,因为myFunction()存储在控制器中?
<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());
}
};
})