2015-05-29 66 views
1

我正在嘗試使用隔離範圍的子指令執行函數。我似乎無法通過隔離作用域執行其父作用域的函數。它只是不起作用。Angular嵌套指令

UsageA: 
<div data-outer data-controller="control"><div data-inner></div></div> 

Usage B: 
<div data-inner data-controller="controlTwo"></div> 


app.controller('control', ['$scope', function($scope){ 
$scope.onOuterChange = function() { 
    alert("Outer Change"); 
} 
}]); 

app.controller('controlTwo', ['$scope', function($scope){ 
$scope.onInnerChange = function() { 
    alert("Inner Change"); 
} 
}]); 

app.directive('outer', function($compile){ 
// Runs during compile 
return { 
    scope: { 
     "onOuterChange": "&", 
    }, 
    controller: function ($scope, $element) { 
    }, 
    link: function ($scope, iElm, iAttrs, controller) { 
     $scope.onInnerChange = function() { 
      alert("Inner Changed"); 
     } 
    } 
} 
}); 
app.directive('inner', function($compile){ 
// Runs during compile 
return { 
    scope: { 
     "onInnerChange": "&", 
    }, 
    controller: function ($scope, $element) { 
    }, 
    link: function ($scope, iElm, iAttrs, controller) { 
     $scope.onInnerChange(); 
    } 
} 
}); 

回答

0

在一個隔離的範圍內,您也必須在html中指定方法。

<div data-outer on-outer-change="onOuterChange()"><div data-inner></div></div> 
+0

什麼'數據控制器= 「控制」'在指令? –

0

你失蹤添加on-outer-change到外部指令,將要傳遞給隔離的範圍指令像on-outer-change="onOuterChange()"函數名。然後,對於內部指令,您應該將該方法傳遞給onInnerChange範圍變量inner指令隔離範圍。

標記

<div data-outer on-outer-change="onOuterChange()"> 
    <div data-inner on-inner-change="onOuterChange()"></div> 
</div> 

代碼

app.directive('outer', function($compile) { 
    // Runs during compile 
    return { 
    scope: { 
     "onOuterChange": "&", 
    }, 
    restrict: 'A', 
    controller: function($scope, $element) {}, 
    link: function($scope, iElm, iAttrs, controller) { 
     $scope.onInnerChange = function() { 
     scope.onOuterChange(); 
     } 
    } 
    } 
}); 
app.directive('inner', function($compile) { 
    // Runs during compile 
    return { 
    scope: { 
     "onInnerChange": "&", 
    }, 
    controller: function($scope, $element) {}, 
    link: function($scope, iElm, iAttrs, controller) { 
     $scope.onInnerChange(); 
    } 
    } 
}); 

Demo here

+0

唯一的問題是外部指令將始終與內部指令一起使用。我希望內部指令承擔該功能總是在那裏..? – MatBee

+0

那麼你應該在內部控制器中使用'require:'^ outer'',這將確保內部總是包含外部作爲父 –

+0

但內部控制器不依賴於外部..只有外部控制器取決於內部。 – MatBee