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

时间:2013-10-03 08:38:30

标签: angularjs angularjs-directive angularjs-scope

如何更新指令范围?

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

我的指示:

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) {
    }]);

点击指令后不会更新。

1 个答案:

答案 0 :(得分:43)

使用$apply方法:

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

说明:How does data binding work in AngularJS?