Angular.js How to update the scope from a directiv

2019-02-06 07:13发布

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.

1条回答
Emotional °昔
2楼-- · 2019-02-06 07:55

Use $apply method:

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

Explanation: How does data binding work in AngularJS?

查看更多
登录 后发表回答