Search code examples
javascriptjqueryangularjsangularjs-ng-click

ng-click does not fire with a function


I am new with Angular and now I have encountered some problems...

So let's say I have a controller called ViewModelController and I use controlleras when I define the routes as following: enter image description here.

And in my template I have just difened two div which seperate the container in two parts:

<div id='viewleft' class="divleft col-md-5"></div>
<div id='viewright' class="col-md-7 divright"></div>

And in ViewModelController, I have some code to render the template when the controller is loaded. The question is that the ng-click I put in all the elements just don't fire and I don't really know where is the problem.

I have tried thing like below but it just does not work.

  var content1 = '<ul><li><button id ="b1" ng-click="vmCtrl.cprint($event.target)">123</button></li><ul>';
  $("#viewleft").html(content1);

Can someone helps me on that? Thank you in advance, best wishes.


Solution

  • You have to compile this html so that angular code will work

    $compile($("#viewleft").contents())(scope);
    

    or better to use a directive that compile html when its value changes.

    app.directive('compile', ['$compile', function ($compile) {
            return function (scope, element, attrs) {
                scope.$watch(
                    function (scope) {
                        // watch the 'compile' expression for changes
                        return scope.$eval(attrs.compile);
                    },
                    function (value) {
                        // when the 'compile' expression changes
                        // assign it into the current DOM
                        element.html(value);
    
                        // compile the new DOM and link it to the current
                        // scope.
                        // NOTE: we only compile .childNodes so that
                        // we don't get into infinite loop compiling ourselves
                        $compile(element.contents())(scope);
                    }
                );
            };
        }]);
    

    in controller you can asssign html to scope variable

    $scope.template= '<ul><li><button id ="b1" ng-click="vmCtrl.cprint($event.target)">123</button></li><ul>';
    

    and on view you can add that

    <div id='viewleft' class="divleft col-md-5" compile="template"></div>
    

    You can refer this docs for $compile.