2017-01-10 93 views
0

我正在嘗試在角es6中開發應用程序。我有一個directve問題。 這裏是我的代碼angularJS ES6指令

export default class RoleDirective { 
    constructor() { 
    this.template=""; 
    this.restrict = 'A'; 
    this.scope = { 
     role :"@rolePermission" 
    }; 

    this.controller = RoleDirectiveController; 
    this.controllerAs = 'ctrl'; 
    this.bindToController = true; 
    } 

    // Directive compile function 
    compile(element,attrs,ctrl) { 
     console.log("df",this) 
    } 

    // Directive link function 
    link(scope,element,attrs,ctrl) { 

     console.log("dsf",ctrl.role) 
    } 
} 

// Directive's controller 
class RoleDirectiveController { 
    constructor() { 
    console.log(this.role) 
    //console.log("role", commonService.userModule().getUserPermission("change_corsmodel")); 
    //$($element[0]).css('visibility', 'hidden'); 
    } 

} 

export default angular 
    .module('common.directive', []) 
    .directive('rolePermission',[() => new RoleDirective()]); 

的問題是我不能讓裏面的構造函數的作用值。 這裏是我的HTML實現

<a ui-sref="event" class="button text-uppercase button-md" role-permission="dfsd" detail="sdfdsfsfdssd">Create event</a> 

如果我安慰這是會得到控制對象。但是在使用this.role時它不會得到任何結果。

+0

你也可以參考[這個答案](http://stackoverflow.com/a/41524591/2435473)。 –

+1

使用ES5你會遇到完全相同的問題。對於這個指令來說,首先要有一個控制器和一個獨立的範圍是沒有意義的。 – zeroflagL

回答

2

好的,所以我設法弄清楚它是如何工作的。

基本上,範圍值無法在控制器的構造函數上初始化(因爲這是在新對象上執行的第一件事),並且還有綁定需要考慮。

還有就是你可以在你的控制器實現,可以幫助你與你的使用情況掛鉤:$onInit

class RoleDirectiveController { 
    constructor() { 
    // data not available yet on 'this' - they couldn't be 
    } 

    $onInit() { 
    console.log(this.role) 
    } 
} 

這應該工作。請注意,這是angular1.5 +不依賴$ scope來保存模型的方式。因爲如果你使用範圍,你可以在控制器的構造函數中注入(注入)。

+0

謝謝你救了我的一天..其實我正在使用bindtocontroller,所以它有它自己的範圍嗎?不是全球範圍。 – user3118041

+0

您正在使用獨立作用域(通過在您的指令'範圍'定義中使用對象來定義)。 'bindToController'是別的東西 - 這基本上告訴角使用控制器對象,而不是$ scope對象 - 但它會被隔離的任何一種方式 –