簡體   English   中英

訪問指令中定義的角度控制器

[英]Accessing angular controller defined within directive

我需要將ng-controller包裝在指令中,並在html中訪問其屬性。 但是,我無法使它正常工作。

這是我的app.js文件內容:

angular.module('myModule', [])
.directive('myDirective', function()
{
   transclude: true,
   template: '<div ng-controller="MyController as ctrl" ng-transclude></div>'
});

我無法訪問MyController中定義的任何屬性(例如消息)。 我的html頁面上的這段代碼不起作用(即消息未打印):

<my-directive>
    {{ ctrl.message }}
</my-directive>

我在這里想念什么嗎?

angular.module('myModule', [])
.controller('MyController', function($scope) {
  $scope.message = 'Hello from Scope';
  $scope.me = this;
  this.scope = $scope;
  this.message = 'Hello from Controller';
  $scope.click = function(scope) {
    alert('Alert message!!!');
  }
  this.click = function(){
    alert('Controllers click!!!')
  }
})
.directive('myDirective', function() {
  return {
    restrict:'E',
    scope: {
      ctrl: "="
    },
    transclude: true,
    template: '<div ng-click="ctrl.scope.click()">'
      +'Scope message:{{ctrl.scope.message}}<br/>Controller message: {{ctrl.message}}<br />'
      + '</div><div ng-click="ctrl.click()">Click me!</div>';
  }
});

您可以嘗試通過這種方式進行操作...希望對您有所幫助... Plunker: 查看所有代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM