-1

I'm trying to load a form using Angular with the following process :

  1. Load values from a PHP script

  2. Load the template on which values have to be rendered

HTML

<form ng-controller="formularCtrl" ng-init="initForm()">
    <div ng-bind-html='form.template | unsafe'></div>
</form>

ANGULAR

angular
    .module('exampleFormular', ['formular.module', 'ngSanitize'])
    .controller('formularCtrl', function ($scope, $http) {

        $scope.form = {};

        $scope.initForm = function () {
            $http.get('ajax/loadForm.php')
            .success(function (data) {
                $scope.form.content = data;
            })
            .then(function() {
                $http.get('templates/formTemplate.html')
                .success(function (data) {
                   $scope.form.template = data;
                });
            });
        };

    })
    .filter('unsafe', function($sce) { return $sce.trustAsHtml; });

PHP

$form = new StdClass();
$form->name->id = 'name';
$form->name->type = 'text';
$form->name->value = 'Test';
echo json_encode($form);
// {"name": {"id":"name", "type":"text", "value":"Test"}}

TEMPLATE

<input 
  type="{{form.content.name.type}}" 
  id="{{form.content.name.id}}" 
  value="{{form.content.name.value}}" />

The current result is my HTML being well formed, and my values being settled.

console.log($scope.form.content.name.value); // Test

But the values are not being rendered in the HTML, resulting on an input with {{form.content.name.value}} inside, instead of 'Test'

I'm not comfortable yet with scope things, but I tried to $scope.$apply() during the AJAX calls or after, with no success (and absolutly no change).

(I also tried to load the template, and then load the values, still not working.)

Clément Malet
  • 5,062
  • 3
  • 29
  • 48
  • Have you tried to [$compile](https://docs.angularjs.org/api/ng/service/$compile) the template ? – AndreiC Mar 22 '15 at 10:21
  • 4
    Try the answer from http://stackoverflow.com/questions/17417607/angular-ng-bind-html-unsafe-and-directive-within-it . It's basically what you want to achieve. – Mateusz Kocz Mar 22 '15 at 10:56

1 Answers1

0

Inside the Ajax success function, do $scope.$apply(function() { $scope.form.template = data; });

Artem K.
  • 804
  • 6
  • 15
  • To avoid the digest error, wrap the $scope.$apply() in a $timeout with 0 delay. This puts the operation in queue once digest is done. You'll need to inject $timeout into the controller. $timeout(function() { $scope.$apply( ... ); }, 0); – Artem K. Mar 24 '15 at 15:48