2016-05-01 150 views
0

我的指令有一个控制器,我试图弄清楚如何从传入的指令中传递一个值。在下面的例子中,'name'无效发布到控制台,但它在呈现时显示在html中。显然我的例子是过于简单化,但你明白了。如何将角度值传递给指令控制器?

angular.module('myApp') 
 
    .directive('helpLabel', function() { 
 
     return { 
 
      restrict: 'E', 
 
      scope: { 
 
       name: '@', 
 
      }, 
 
      template: '<span>{{name}}</span>', 
 
      controller: function ($scope) {     
 
       console.log(name); 
 
      } 
 
     }; 
 
    });
<helpLabel name="test"></helpLabel>

回答

0

这是因为当它被呈现到HTML,你中封装名称{{}}。如果你不想访问你的指令中的name属性,你必须改变你的代码。

angular.module('myApp') 
.directive('helpLabel', function() { 
    return { 
     restrict: 'E', 
     scope: { 
      name: '@', 
     }, 
     template: '<span>{{name}}</span>', 
     controller: function ($scope) {     
      console.log($scope.name); 
     } 
    }; 
}); 
0

在你的代码,console.log(name);,变量name不知道你的指令,因此不能够访问它,但由于角度做了结合'name'变量,它可以呈现{{name}}

您应该访问变量name作为$scope.name作为变量name存在于当前范围内。

修改代码如下:

angular.module('myApp') 
    .directive('helpLabel', function() { 
     return { 
      restrict: 'E', 
      scope: { 
       name: '@', 
      }, 
      template: '<span>{{name}}</span>', 
      controller: function ($scope) {     
       console.log($scope.name); 
      } 
     }; 
    }); 
相关问题