Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.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
Angularjs ng单击“不在我的指令中工作”_Angularjs_Angularjs Directive_Angularjs Ng Click - Fatal编程技术网

Angularjs ng单击“不在我的指令中工作”

Angularjs ng单击“不在我的指令中工作”,angularjs,angularjs-directive,angularjs-ng-click,Angularjs,Angularjs Directive,Angularjs Ng Click,我这里有一个非常简单的场景 <body> <h1 nametag name="name" logsomthing="logsomthing()">Hello {{name}} <a href="#" ng-click="logsomthing()">Click here for alert</a></h1> </body> 它应该在单击时发出警报(“它正在工作”),但什么也没有发生。我找不到解决办法 以下是如果您想让它工作

我这里有一个非常简单的场景

<body>
<h1 nametag name="name" logsomthing="logsomthing()">Hello {{name}} <a href="#" ng-click="logsomthing()">Click here for alert</a></h1>
</body>
它应该在单击时发出警报(“它正在工作”),但什么也没有发生。我找不到解决办法


以下是

如果您想让它工作,您需要在指令中添加一个模板:

指令:

angular.module('test', [])
.directive('nametag', function() {

 return {
  scope: {
    name: '@',
  },
  template:'Hello {{name}} <a href="#" ng-click="logsomthing()">Click here for alert</a>',
  controller: function($scope, $attrs, $log) {
      //$scope.name = 'John Doe';    // Not necessary anymore, sent by the view

      $scope.logsomthing = function() {
        alert('it is working');
      }
    },
    link: function(scope, elem, attrs) {

    }
};
<body>
  <h1 nametag name="John Doe"></h1>
</body>
角度模块('test',[]) .directive('nametag',function(){ 返回{ 范围:{ 名称:“@”, }, 模板:'Hello{{name}}', 控制器:函数($scope、$attrs、$log){ //$scope.name='John Doe';//不再需要,由视图发送 $scope.logsomthing=function(){ 警报(“它正在工作”); } }, 链接:功能(范围、要素、属性){ } }; }))

查看:

angular.module('test', [])
.directive('nametag', function() {

 return {
  scope: {
    name: '@',
  },
  template:'Hello {{name}} <a href="#" ng-click="logsomthing()">Click here for alert</a>',
  controller: function($scope, $attrs, $log) {
      //$scope.name = 'John Doe';    // Not necessary anymore, sent by the view

      $scope.logsomthing = function() {
        alert('it is working');
      }
    },
    link: function(scope, elem, attrs) {

    }
};
<body>
  <h1 nametag name="John Doe"></h1>
</body>


您也不需要定义3次函数logsomthing

,只需删除指令返回函数中的
scope
对象,它就可以正常工作了。无需传递任何
scope
,因为作用域已在指令本身中。Hello{{name}此html不在指令的作用域中。因此,无法使用此方法访问$scope.logsomthing。要实现这一点,您需要指定指令模板。很抱歉,他在指令本身中声明了
$scope.name
,因此无需传递
name
scope。@AlbertoI.N.J。谢谢你发现了。我用最简单的方法更新了我的答案,我可以像这样使用ng click吗?