2016-05-01 152 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); 
      } 
     }; 
    }); 
相關問題