samedi 9 mai 2015

AngularJS: Custom directive doesn't get compiled

I want to disable a button while a factory AJAX request is running (after the button was clicked) in a generic way and I used this SO answer as a starting point on how to do that, but I can't get my custom directive click-disable to execute the controller method (using ng-click works fine).

I suspect my directives doesn't get "compiled" at page load, directives with simple templates also don't seem to work.

js/services.js:

var raspiSurveillanceServices= angular.module('raspiSurveillanceServices', ['ngResource']);

raspiSurveillanceServices.factory('Camera', ['$resource',
    function($resource) {
        return $resource('/api/cameras/:id');
    }]);

js/directives.js:

var raspiSurveillanceDirectives = angular.module('raspiSurveillanceDirectives', []);

raspiSurveillanceDirectives.directive('clickDisable', function() {
    return {
        restrict: 'A',
        scope: {
            clickDisable: '&'
        },
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                element.prop('disabled', true);

                scope.clickDisable().finally(function() {
                    element.prop('disabled', false);
                });
            });
        }
    };
});

js/controllers.js:

raspiSurveillanceControllers.controller('CameraListCtrl', ['$scope', 'Camera', function ($scope, Camera) {

    $scope.cameras = Camera.query();

    $scope.deleteCamera = function(camera) {
        return Camera.delete({ id: camera.id}).$promise.then(
            function(value) {
                // Remove item from array
                var index = $scope.cameras.indexOf(camera);
                $scope.cameras.splice(index, 1);
            },
            function(error) {
                alert("Delete failed");
            }
        )
    };

}]);

js/app.js:

var raspiSurveillanceApp = angular.module('raspiSurveillanceApp', [
  'raspiSurveillanceControllers',
  'raspiSurveillanceServices',
  'raspiSurveillanceDirectives',

  'xeditable'
]);

.blade.php:

<tr ng-repeat="camera in cameras">
    ...
    <button class="btn btn-danger" click-disable="deleteCamera(camera)">Delete</button>
</tr>
...
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-resource.min.js"></script>

<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
<script src="js/directives.js"></script>

Aucun commentaire:

Enregistrer un commentaire