Angular.js如何从指令更新范围?

时间:2022-04-30 11:21:46

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 个解决方案

#1


40  

Use $apply method:

使用$ apply方法:

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

Explanation: How does data binding work in AngularJS?

说明:数据绑定如何在AngularJS中工作?

#1


40  

Use $apply method:

使用$ apply方法:

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

Explanation: How does data binding work in AngularJS?

说明:数据绑定如何在AngularJS中工作?