![](/img/trans.png)
[英]AngularJS change in directive's scope not updating parent controller scope
[英]AngularJS - Updating variables within the parent controller scope from a function in a transcluded directive scope
父控制器范圍變量如何從已轉換的指令范圍的函數中更新?
我通過以下方式使用轉換將指令嵌入到另一個指令中:
<my-table>
<my-getter-button></my-getter-button>
</my-table>
my-table和my-getter按鈕的代碼如下:
my-table
模板:
<table>
<tr ng-repeat="item in items">
<td data-id="{{item.Id}}" ng-transclude></td>
</tr>
</table>
my-table
指令:
.directive('myTable', function () {
return {
transclude: true,
restrict: 'E',
templateUrl: 'views/mytable.html',
scope: false
};
});
my-getter-button
指令(帶模板):
app.directive('myGetterButton', function () {
function link(scope, element) {
scope.finalizeGet = function () {
var id = element.parent().data('id');
scope.clear(); // <-- works fine (from parent controller)
scope.get(id) // <-- works fine (from parent controller)
.success(function (data) {
// The line below was supposed to
// update the variables within the parent controller:
scope.$parent.instance = data; // or scope.instance = data;
angular.element('#detailsModal').modal('show');
})
.error(function (data) {
scope.errors = data;
});
};
};
return {
restrict: 'E',
template: '<button class="btn btn-info" ng-click="finalizeGet()">' +
'<span class="glyphicon glyphicon-book"></span>' +
'</button>',
scope: false,
link: link
};
});
我期待scope.$parent.instance = data; // or scope.instance = data;
scope.$parent.instance = data; // or scope.instance = data;
更改父控制器的scope.instance
但它沒有。
我找到了解決自己問題的方法。 原來我需要的是一個setter函數。 我在控制器中添加了以下內容:
// Set current model instance of scope.
$scope.setInstance = function(data) {
$scope.instance = data;
};
並調用setter函數(而不是賦值操作),如下所示:
// ...
.success(function (data) {
scope.setInstance(data);
angular.element('#detailsModal').modal('show');
})
// ...
它更新了父控制器范圍中的變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.