1

I am trying to change a text to input['type="text"] element with a button appended for updating it. However, when i attach a function($scope.commit_update) on its ng-click event,the function is not firing.

$scope.commit_update = function(id){
      console.log(id);
}
$scope.update = function($service_id){

    var current_text = document.getElementById($service_id).innerHTML;
    if(/<[a-z][\s\S]*>/i.test(current_text) == false){
        var vars = $service_id.split('-');
        var node = '<div class="input-group" style="width:200px;"><span class="input-group-addon" style="cursor:pointer;" ng-click="commit_update('+vars[1]+')">Save</span><input type="text" class="form-control" value="'+current_text+'" style="width:200px;"></div>';   
        document.getElementById($service_id).innerHTML = node;
    }

}
2
  • 1
    Please post HTML + directive or u post Fiddle/Plunker. Thanks Commented Oct 13, 2013 at 12:25
  • jsfiddle.net/jT2Rw/1 Commented Oct 13, 2013 at 12:36

1 Answer 1

7

Its not good idea to do any manipulations with DOM in controller. Use directive for that.

Angular doesn't know about dynamic HTML you try to append. To make ng-click to work we need to compile dynamic HTML source by using $compile service.

Here is your modified Fiddle:

Demo Fiddle

HTML

        <tbody>
            <tr>
                <td id="service-1" fess>Test</td>
                <td> <a class="btn btn-primary btn-large" ng-click="update()"><i class="glyphicon glyphicon-pencil"></i></a>
 <a class="btn btn-primary btn-large"><i class="glyphicon glyphicon-trash"></i></a>

                </td>
            </tr>
        </tbody>

JS

fessmodule.directive('fess', function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs) {
            scope.heyFess = function () {
                console.log('k');
                var current_text = document.getElementById("service-1").innerHTML;
                if (/<[a-z][\s\S]*>/i.test(current_text) == false) {

                    var node = '<div class="input-group" style="width:200px;" ><span class="input-group-addon" style="cursor:pointer;" ng-click=alertMe()>Save</span><input type="text" class="form-control" value="' + current_text + '" style="width:200px;"></input></div>';

                    var e = angular.element(node);
                    $compile(e.contents())(scope);
                    elm.replaceWith(e);
                }
            };
        }
    };
});
Sign up to request clarification or add additional context in comments.

Comments

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.