whatscool
whatscool

Reputation: 317

How do I run a function on some text after the view is updated?

I have inherited an angularJS application and I'm not sure how to approach this problem.

My page has a table of elements with values attached from the model with data-ng-bind. One of these elements is data.name:

<div class="component-name__plan_data_name" data-ng-bind="data.name">
&nbsp;
</div>

There are radio buttons at the top of the table to toggle between different views of the table, toggling these buttons updated the table view to new data

<input type="radio"
       data-ng-model="mobile.capacityContractMap[mobile.selectedCapacity]"
       data-ng-value="'{{contract}}'">

I need a simple operation to run on the text in the data.name field before it is displayed in the view. I want to interpret br tags as line breaks (but no other html).

I wrote a very simple jquery function to do this:

function changeText() {
    elementstring = ".component-name__plan_data_name";
    toChange = "&lt;br&gt;"
    changeTo = "\<br\>"
    $(elementstring).each(function(){
        var text = $(this).html();
        var newtext = text.replace(toChange,changeTo);
        $(this).html(newtext);
    })
}

I run my jquery function after the elements have loaded by calling it in an ng-init of an element loaded at the bottom of my component and this works - the initial values in my data.name field have a line break applied where appropriate.

My problem is that I cannot get the function to run when the radio button is toggled, the model is changed and the data.name fields are updated. I'm not sure the best way to approach this.

I have tried using $scope.$listen in a variety of ways in the controller. I've tried using ng-change on the radio button. I can't get either method to work.

Can anyone advise me the best approach to this? Thanks

Upvotes: 0

Views: 25

Answers (1)

georgeawg
georgeawg

Reputation: 48968

Use a custom directive:

app.directive("bindChangeText", function() {
    return {
        link: postLink,
    };
    function postLink(scope,elem,attrs) {
        scope.$watch(attrs.bindChangeText, function(value) {
            if (typeof value != "string") return;
            var toChange = "&lt;br&gt;"
            var changeTo = "\<br\>"
            var newtext = value.replace(toChange,changeTo);
            elem.html(newtext);
        });
    }
})

Usage

<div class="component-name__plan_data_name"
     bind-change-text="data.name">
</div>

For more information, see

Upvotes: 1

Related Questions