Policy to create div, label, and input

1

Hello, I created a directive to create a div, a label, and an input, but the ng-model attribute is not working.

In the example, the created dynamically does not work which is the first, and the created one that is the second one works.

link

I've made several attempts and nothing.

Thank you in advance.

    
asked by anonymous 01.12.2016 / 13:54

1 answer

2

What's missing in your code is compiling html with a scope so it knows who to bind the models to.

Take a look at the fork I made of your plnkr .

But to make it clear, take a look here:

Inject $compile into your directive as it will be responsible for compiling the html you typed dynamically in your directive.

app.directive('divCadastro', ['$compile', function($compile) {...

And at the time of compiling% compile your html by passing the scope of your controller:

element.append($compile(input)(scope.$parent));

Take a look at the $ compile documentation when you can, but get ahead.

$compile({html a ser compilado})({escopo para fazer bind})

I'm calling the scope so element.append() because you want to bind with the scope of the parent controller's policy. If you pass only scope.$parent the angle will try to bind with your own directive.

UPDATE

I saw your question about the dynamic data not updating scope . Simply initialize the variable in the controller:

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.propriedade = {};
  $scope.manipulaPropriedade = function(propriedade) {
    console.log(propriedade)         ;
  }
});

It is not a good practice to create dynamic variables in $scope . Imagine someone doing maintenance trying to guess where this variable comes from, called later in some method.

    
01.12.2016 / 14:16