2016-10-28 118 views
0

我有兩個指令,隔離共用,所述隔離指令通過雙向直接結合共用指令但共用指令不使用隔離範圍,是創建它自己的。角度範圍,神祕?

的目標是,隔離指令應變化的時候,共享指令變化作出迴應的雙向綁定。

<body ng-app="app"> 
    <div ng-controller="main as $ctrl"> 
    <h3>Main data: {{$ctrl.data.bind}}</h3> 
    <isolated bind="$ctrl.data.bind"></isolated> 
    </div> 
</body> 

angular.module("app", []) 
.controller("main", function() { 
    this.data = { 
    bind: 123 
    } 
}) 
.directive("isolated", function() { 
return { 
    scope: { 
    bind: '=' 
    }, 
    bindToController: true, 
    template: '<div><h3>Parent directive data: {{$ctrl.bind}}</h3> </div>' 
      + '<input type="text" shared ng-model="$ctrl.bind" />', 
    controller: function() { 
    this.changed = function() { 
     console.log('Data changed: ' + this.bind); 
    } 
    }, 
    controllerAs: '$ctrl', 
    link: { 
    pre: function($scope) { 
     console.log("Parent data: " + $scope.$ctrl.bind); 
    } 
    } 
} 
}) 
.directive("shared", function() { 
    return { 
    restrict: 'A', 
    require: { 
     ngModel: '^' 
    }, 
    bindToController: true, 
    link: function($scope) { 
     console.log('Current data in shared: ' + $scope.$ctrl.bind) 
    }, 
    controller: function() { 
     this.$postLink = function() { 
     this.ngModel.$modelValue = 321; 
     } 
    }, 
    controllerAs: '$ctrl' 
    } 
}); 

在這裏,我有一個Plunker

+0

問題在於您的共享指令。 'controllerAs:'$ ctrl''將其改爲'vm'加載文本框中的值。 但後鏈接功能不會更改值。 –

回答

0

Gourav加爾格是正確的。由於共享範圍,第二個指令聲明覆蓋了$scope.$ctrl字段。無論如何,第二個聲明中的controllerAs屬性是不需要的,因爲您從不訪問模板中的控制器屬性。如果最終需要在模板中使用第二個指令控制器信息,則需要將其名稱聲明爲$ctrl以外的其他名稱,或者更好的是,使用require語法來要求第一個指令中的第二個指令。這將把第二個指令的控制器綁定到第一個指令的控制器上的一個屬性。

有關require的更多信息,請參閱角度指令指南here的「創建指令通信」部分。

祝你好運!