[英]How to retrieve values from a custom directive and pass them to a controller
[英]How to get modified values from controller to custom directive?
我在控制器中定義了一個變量,並將此值分配給了定制指令的一個屬性。 因此,基於此值,我正在顯示模式框模板。 現在,如果我單擊模態框模板中的“取消”按鈕,則它將從控制器中調用一個函數,該函數會將變量值修改為false,但不會隱藏彈出框。 請幫助我修復它。
(function () {
'use strict';
angular.module('module1').directive('myDirective', function () {
function linkFunction(scope, elem, attrs) {
//scope.openvalue = attrs.openvalue;
scope.closevalue = false;
scope.close = function () {
console.log("Inside Close");
scope.openvalue = false;
scope.closevalue = false;
};
};
return {
templateUrl: 'confirmTemplate.html',
restrict: 'E',
link: linkFunction,
scope: {
confirmtext: '@',
openvalue: '=',
closeconfirm: '&',
submitconfirm: '&'
},
controller: ['$scope', function ($scope) {
$scope.$watch('openvalue', function () {
console.log("OpenValue : " + $scope.openvalue);
});
}]
};
});
})();
以下是用於打開此模式的html。
<div class="col-xs-12 options" ng-click="cntrl.flag1 = true">
<div class="row">
<myDirective openvalue="cntrl.flag1" confirmtext="This is the text from directive"
closeconfirm="cntrl.closeconfirm()" submitconfirm="cntrl.submitconfirm()"></myDirective>
<div class="col-xs-9 no-left-right-padding">My text</div>
</div>
</div>
而且我想在html模板中更新openvalue的值,但是它不起作用。
在這里編寫代碼會更清楚,但是我認為問題是當您從controller調用函數時,它實際上並沒有修改controller范圍的變量,而是modal的scope 。
在AngularJS范圍內,子范圍內繼承變量的任何更改都將創建一個本地版本。
根據您的話語,當您打開模式窗口時,它將創建一個新的子作用域,並且當您從控制器調用函數以修改該作用域變量時,您實際上是在修改該子作用域變量,而不是控制器的。
您可以簡單地添加console.log($scope.$id);
在控制器和函數中,那么您應該能夠看到作用域ID是不同的。
該小提琴將為您提供想法,按Esc
鍵關閉模式窗口。 但是,正如我所說,最好使用您的代碼來解決確切的問題。
根據您的代碼,快速解決方案是將cntrl
對象分配給指令,這將確保您的指令引用同一對象。
將模態更改為
<myDirective cntrl="cntrl" confirmtext="This is the text from directive"></myDirective>
在您的指令中
scope: {
confirmtext : '@',
cntrl : '='
},
在您的linkFunction中
function linkFunction(scope, elem, attrs){
scope.close = function(){
scope.cntrl.flag1 = false;
}
你仍然可以訪問closeconfirm
和submitconfirm
由$scope.cntrl.closeconfirm
和$scope.cntrl.submitconfirm
分別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.