Maxime
Maxime

Reputation: 560

Set ng-model after rendering JSP page

I'm using AngularJS, Spring MVC & JSP in a project. I need to do this kind of thing :

<div class="hide" ng-app ng-controller="myCtrl">
    <span ng-model="myValue">${valueToRender}</span>
</div>

After rendering, let's say I get this HTML :

<div class="hide" ng-app ng-controller="myCtrl">
    <span ng-model="myValue">42</span>
</div>

I would like, in the Angular Controller, to access the value of myValue, but the browser says that myValue is undefined.

Here is the javascript :

function myCtrl($scope) {
    console.info($scope.myValue); //Browser tells me that is undefined
}

Thank you for your help.

Upvotes: 1

Views: 1042

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40318

ng-model is inappropriate for this, besides it only applies to input elements (not <span>s). I'd suggest using a directive:

Target markup:

<div class="hide" ng-app ng-controller="myCtrl">
    <span server-data="myValue">${valueToRender}</span>
</div>

Directive:

angular.module("...").directive("serverData", function() {
    return {
        scope: false,
        link: function(scope, element, attrs) {
            scope[attrs.serverData] = element.text();
        }
    };
});

This directive with the HTML template above would put the value "42" (string) in the scope, under the name myValue. (This code is untested just to demonstrate the general idea.)

But, are you sure this is the way to implement client-server communication?

Upvotes: 2

Related Questions