0

I have a directive like this.

app.directive('updateinfo', function() {
    function link(scope, element, attrs) {
      function update(){
         var str = '<input type="text" ng-model="scope.log1" />';
         element.html(str);    
      }
      update();
    }
    return {
      link: link
    };
});

The directive shows a text input box, but it does not show the scope.log1value and the changes made in the textbox are not reflected in the scope variable. I want to use the link function because I want to access other scope variables. Is there a way to use link function and still bind data to scope variable.

I appreciate any help.

1
  • You need to use $compile if you want to directly modify the DOM. Commented Apr 24, 2015 at 11:21

2 Answers 2

2

First, you must not write scope or $scope into the DOM.
Secondly, you need to compile your content

app.directive('updateinfo', function($compile) {
     function link(scope, element, attrs) {
          var str = '<input type="text" ng-model="log1" />';
          element.html(str);   
          $compile(element.contents())(scope);
     }
     return {
          link: link
     };
});
Sign up to request clarification or add additional context in comments.

Comments

0

This works for me

.directive('updateinfo',['$compile', function($compile) {
    function link(scope, element, attrs) {
      function update(){
         var str = '<input type="text" ng-model="log1" />';
         element.html(str);    
      }
      update();
      element.replaceWith($compile(element.html())(scope));
    }
    return {
      link: link

    };
}]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.