Angular.js How to update the scope from a directive?

26,570

Use $apply method:

  element.click(function() {
      scope.$apply(function(){
           scope.text = '2';
      });
  });

Explanation: How does data binding work in AngularJS?

Share:
26,570
ExyTab
Author by

ExyTab

Updated on April 17, 2020

Comments

  • ExyTab
    ExyTab about 4 years

    How can I update scope in directive?

    <div ng-controller="MyCtrl">
        <p t></p>
    </div>
    

    My directive:

    var myModule = angular.module('myModule', [])
        .directive('t', function () {
            return {
                template: '{{text}}',
                link: function (scope, element, attrs) {
                    scope.text = '1';
                    element.click(function() {
                         scope.text = '2';
                    });
                }
            };
        })
        .controller('MyCtrl', ['$scope', function ($scope) {
        }]);
    

    After click directive does not update.