Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript $compile在回调内部不工作_Javascript_Angularjs_Angularjs Directive - Fatal编程技术网

Javascript $compile在回调内部不工作

Javascript $compile在回调内部不工作,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我有一个AngularJS指令,它在回调click()函数中调用$compile。然而,这些内容似乎没有得到编译 var testApp = angular.module('testApp', []); testApp.controller('TestController', function($scope) { $scope.user_name = 'George'; }); testApp.directive('testDirective', function($compil

我有一个AngularJS指令,它在回调click()函数中调用$compile。然而,这些内容似乎没有得到编译

var testApp = angular.module('testApp', []);

testApp.controller('TestController', function($scope) {
  $scope.user_name = 'George';
});    

testApp.directive('testDirective', function($compile) {
  return {
    template: 'Click Here',
    link: function(scope, element, attrs) {

      $(element).click(function() {
        $('#externalDiv2').html('{{user_name}}, you clicked the button.');
        $compile($('#externalDiv2')[0])(scope);
      });
    }
  };
});
在上面的示例中,#externalDiv2仍然显示“{user_name}}”,而不是使用scope对象中的用户名插入它

我做错了什么


当您使用click函数时,它是Jquery的一部分,不修改绑定,您必须调用一个可以更新绑定的函数。我们对scope所做的。$apply或$scope。$apply。

{{
{{
不同,因为大括号之间有一个空格。是的,我的问题实际上是关于#externalDiv2中的文本。也就是说,因为您需要执行
scope。$apply()
手动调用摘要循环,因为您是在一个不在angular上下文中的click事件中执行此操作的。哦,太酷了,谢谢@PSL!为什么添加了这一行。请在回答中也做一些解释。@PSL现在解释行了吗?
var testApp = angular.module('testApp', []);

testApp.controller('TestController', function($scope) {
  $scope.user_name = 'George';
});    

testApp.directive('testDirective', function($compile) {
  return {
    template: 'Click Here',
    link: function(scope, element, attrs) {

      $('#externalDiv1').html('{{user_name}}, the directive has loaded.');
      $compile($('#externalDiv1')[0])(scope);

      $(element).click(function() {
        $('#externalDiv2').html('{{user_name}}, you clicked the button.');
        $compile($('#externalDiv2')[0])(scope);
          scope.$apply();//THIS LINE HAS BEEN ADDED
      });
    }
  };
});