コントローラー変数を子ディレクティブから更新したいとします。 コントローラー変数を更新しましたが、この値はビュー内で変更されません。 私は$ scopeを使用する必要があります。$ apply()? $ダイジェスト?コントローラー変数を更新し、view(from 1.5)のビューで使用します。
これはhttp://plnkr.co/edit/zTKzofwjPfg9eXmgmi8s?p=preview
jsのは、あなたが私のコードをきれいにするために他の提案を持っている場合、
UPDATEそれをしてください共有
var app = angular.module('app', []);
app.controller('parentController', function($scope) {
this.myVar = 'Hello from parent';
this.refreshMyVar = function(data) {
this.myVar = data.name;
console.log('>> this.myVar', this.myVar);
};
});
app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
template: '<input type="file" />',
bindToController: {
attrFromParent: '='
},
controller: 'directiveController as directiveCtrl',
link: function(scope, el, attr, ctrl) {
el.bind('change', function(e) {
ctrl.onChange(e.target.files[0]);
});
}
};
});
app.controller('directiveController', function() {
this.onChange = function(file) {
this.attrFromParent(file);
};
});
htmlファイル
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<body>
<div ng-app="app" ng-controller="parentController as parentCtrl">
<h1> >> {{parentCtrl.myVar}}</h1>
<p><my-directive attr-from-parent="parentCtrl.refreshMyVar" /></p>
</div>
</body>
</html>
を提出私のコードです
app.controller('parentController', function($scope) {
this.myVar = 'Hello from parent';
this.refreshMyVar = data => {
this.myVar = data.name;
console.log('>> this.myVar', this);
$scope.$parent.$apply(); // solve my problem
};
});
$ scope。$ parent。$ apply();誰かが他の命題を持っている場合、私は非常に満足していません
まず、my-directive要素の構文を誤って記述しました。自己閉鎖要素であってはなりません。 –