Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

AngularJS Bind $scope variable


I try to build this directive in angularJS, and I face this problem which I try to bind to HTML, object property which its name come from another variable like below example

angular.module('ng.box', codeHive.angular.modules)
.directive('boxView', function($compile) {
return {
    link: function(scope, element, attrs, ngModelCtrl) {
       var name = 'exampl';
        var htmlTemplate = '<div instance="'+scope[name].innerVal +'"  </div> ';

        var el = angular.element('<div/>');
        el.append(htmlTemplate);
        $compile(el)(scope);
        element.append(el);
    },
  };
})

I try to figure out how to bind this object property to the instance attribute in HTML element

 var htmlTemplate = '<div instance="'+scope[name].innerVal +'"  </div> ';

Any help please


Solution

  • Pretty simple:

    var htmlTemplate = '<div instance="' + name + '.innerVal"  </div> ';
    

    PS. BTW, these lines should be swapped:

        element.append(el); // this should be first line
        $compile(el)(scope); // this should be second line
    

    The reason is that directives in the template being appended that require other directives on the parent elements will not be able to find them when compiled "offline".