I want to rewrite this fiddle as a directive. It was my very first experiment with Angular. I actually got the idea from w3 schools, dom manipulation
I thought my fiddle was nicely written, however, after reading that coupling behaviour to a directive may be an anti design pattern I am again at a loss. So designing an element as
<photo>
<img ng-click="toggleOnOff()" ng-src="{{'togglePhotoSrc()'}}"/>
Does not seem to be recommended. Right?
I want to solve this as an isolated scope. I'd like the two urls to be known in the directive. If possible, I'd like to do this without using element.addClass.
Design advice appreciated as much as a working example.
EDIT: I got this working but would appreciate comments especially in terms of better design!!
<body ng-controller="MyCtrl">
<div><pre>State is on = {{isOn}}</pre></div>
<div>
<input type="checkbox" ng-model="isOn" />Switch the light
<a toggle="isOn">
<img ng-src="{{ getToggledUrl() }}">
</a>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script>
angular.module('app', [])
.directive('toggle', function() {
return {
scope: {
toggle: "="
},
link: function($scope, element, attrs) {
element.click(function() {
$scope.$apply(function() {
var src = element.find('img').attr('src');
$scope.toggle = !$scope.toggle
})
})
}
}
})
function MyCtrl($scope) {
$scope.isOn = false;
$scope.onUrl = "http://www.w3schools.com/js/pic_bulbon.gif";
$scope.offUrl = "http://www.w3schools.com/js/pic_bulboff.gif";
//toggle image
$scope.getToggledUrl = function() {
return $scope.isOn ? $scope.onUrl : $scope.offUrl;
};
}