0

I have in my code, some html elements that are added later on the page. but when you add it later, the directive ng-click does not work.

Another solution I've tried was to call a node method on this later added element using onclick attribute, but it means call a angularJs method outsite the controller and it's not possible (if so, could be a nice solution for many type of problems)

here's the jsfiddle example: http://jsfiddle.net/hugoofab/wktqrhv3/1/

here's the markup:

<div ng-app="myApp" ng-controller="MyController" >
<button type="button" ng-click="testFunction('this will work')">STEP 1. this will work</button>

<button type="button" ng-click="addElement()" >STEP 2. add button</button>
    <div id="foodiv"></div>

<button type="button" onclick="anotherWay()" >STEP 4. another way</button>

Here's the javascript:

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

function anotherWay ( ) {
    alert("another way would be call node method outside, but how to do it?")
    // ohhh man.. what I'll code here?
    //myApp.controller.scope()..... I really don't know
}

myApp.controller('MyController', function($scope) {

    $scope.testFunction = function ( a ) {
        alert(a)
    }

    $scope.addElement = function ( ) {
        document.getElementById('foodiv').innerHTML = '<button type="button" ng-click="testFunction(\'this will not work\')">STEP 3. this will not work</button>' ;
    }

});

Thank's!

Hugo Ferreira
  • 184
  • 13
  • 2
    see about `$compile` service. But anyway - if you work with dom in angular controller - you do something wrong, try see [this post](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background) – Grundy Jun 11 '15 at 15:18
  • why do you want to add elements *later* on the page? There is probably a more idiomatic way to do what you are trying to achieve. – Davin Tryon Jun 11 '15 at 15:20
  • why don't think of SPA, which will change the html on step transitions – Pankaj Parkar Jun 11 '15 at 15:22
  • Thank's everyone, I'm reading little more to think more angular way... – Hugo Ferreira Jun 11 '15 at 16:13

1 Answers1

0

It seems you're doing things in a "non-angular" way...

First of all, this happens to you because you add these elements after angular has $compiled the view.

One way of doing this the "angular way", is using an ng-show/ng-hide directive with your buttons, and showing/hiding them using the controller.

Another way is having something like this:

$scope.buttons = [{ }, { }];

And adding buttons to this array using the controller. Then render this array in your view using ng-repeat.

idoberko2
  • 136
  • 2