4

I am trying to replicate the following jsfiddle using only angular (no jquery).

http://jsfiddle.net/E7xER/381/

Essentially I would like to set up event listeners to bind to elements which don't yet exist. With jquery this can be accomplished with:

$('#container').on('click', '.class', myFunction);

What is the "angular way" to bind to elements that do not yet exist? I suspect I will need to create a new directive to do this, and I believe I may need to inject $compile to compile the newly added DOM elements. I am new to AngularJS though and I am unsure how to implement this.

2 Answers 2

3

http://jsfiddle.net/dB7nt/

Like this?

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

myApp.directive('myWidget', function() {
    var linkFn;
    linkFn = function(scope, element, attrs) {
        scope.boxes = [];

        scope.addBox = function () {
            scope.boxes.push({});
        };

        scope.color = function (b) {
            b.isRed = true;
        }
    };
    return {
        restrict: 'E',
        link: linkFn,
        template: '<button ng-click="addBox()">Add a box</button><BR/><div><div class="box" ng-repeat="b in boxes" ng-click="color(b)" ng-class="{ red: b.isRed }"></div></div>',
        scope: {
        }
    };
});
Sign up to request clarification or add additional context in comments.

Comments

2

Personally I would create a controller for this.

Here's your fiddle using a controller.

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

myApp.controller("BoxCtrl", function ($scope) {
    $scope.boxes = [];
    $scope.addBox = function () {
        $scope.boxes.push(0);
    };
    $scope.colorBox = function (box, index) {
        $scope.boxes[index] = 1;
    };
    $scope.isBoxClicked = function (box) {
        return {
            'background-color': (box == 1 ? 'red' : '#abc')
        };
    };
});

1 Comment

I definitely would like to evaluate/understand the controller approach as well. In your fiddle the first box that is not red turns red, rather than whichever box is clicked. I believe this must be a minor error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.