简体   繁体   中英

How to bind dynamically generated elements in Angular.js?

I'm getting started with Angular.js directives, so I'm dynamically generating DOM with custom directives.

The simplified version of my directive is:

angular.module('app', [])
  .controller('Controller', ['$scope',
    function($scope) {
      $scope.name = "André Pena";
      $scope.email = "andrerpena@gmail.com"
    }
  ])
  .directive('gText', function() {
    return {
      restrict: 'E',
      link: function(scope, element, attrs) {
        //input
        var input = angular.element("<input/>");
        input.attr("type", "text");
        input.addClass("form-control");
        input.attr("placeholder", attrs.placeholder);
        input.attr("name", attrs.property);
        element.append(input);
      }
    };
  });

And a simple use of this directive is:

<g-text label="E-mail" property="email" placeholder="Enter some e-mail"></g-text>

As you can see, I'm creating an input tag dynamically using an Angular.js element . I want to bind the value of this element with the property specified in the property attribute. In this case, I want the value of the input to be the email scope property (andrerpena@gmail.com).

How to achieve that?

When you create a dynamic element, you have to compile it into the directive. For that, you have to use $compile function of angular. I've done it for you.

have a look here : http://jsfiddle.net/3hJmz/1/

var app = angular.module('app', []);
app.controller('Controller', ['$scope',

function ($scope) {
    $scope.name = "André Pena";
    $scope.email = "andrerpena@gmail.com";
    console.log($scope.email);
}]);
app.directive('gText', function ($compile) {
    return {
        restrict: 'E',
        scope: {
            info: "=property"
        },

        link: function (scope, element, attrs) {

            var input = angular.element("<input/>");
            input.attr("type", "text");
            input.attr("placeholder", attrs.placeholder);
            input.attr("value", scope.info);

            var linkFn = $compile(input);
            var content = linkFn(scope);
            element.append(content);
        }
    };
});

any more concern, revert back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM