Search code examples
jqueryangularjsangular-ngmodel

Angular programmatically binding ng-model


I have an inline label which when clicked will be replaced with input box to edit the content.

<div ng-app>
    <div ng-controller="TempController">
        <label ng-model="Data" class="editable-lbl">{{ Data }}</label>
        <br /><br /> 
        <button ng-click="Save()">Save</button>
    </div>
</div>

The problem is after editing, it will not update the variable inside the scope.

function TempController($scope)
{
    $scope.Data = 'Hi! Im enteng, Click me to edit';

    $scope.Save = function()
    {
         alert($scope.Data);
    }
}

$(document).on("click", "label.editable-lbl", function () {
     var txt = $(".editable-lbl").text();
     $(".editable-lbl").replaceWith("<input ng-model='Data' class='editable-lbl-input' />");
     $(".editable-lbl-input").val(txt);
});

$(document).on("blur", "input.editable-lbl-input", function () {
     var txt = $(this).val();
     $(this).replaceWith("<label class='editable-lbl'></label>");
     $(".editable-lbl").text(txt);
});

Check this fiddle for live example Fiddle

I tried to bind ng-model in

$(".editable-lbl").replaceWith("<input ng-model='Data' class='editable-lbl-input' />");

but still when I click the save button, the same value will prompt.


Solution

  • You have at least two problems:

    • 1st off when you try to add any element, in your case for example: <input ng-model='Data' class='editable-lbl-input' /> you need to compile it first by using $compilein order to tell to Angular to put this content under digest cycle.

    • Any DOM manipulation/update write in Directives only! Otherwise you brake Angular concept


    You can find this example helpful: Fiddle