gpt4 book ai didi

javascript - 更新 Controller 变量并在指令 View 中使用它( Angular 1.5)

转载 作者:行者123 更新时间:2023-12-03 05:59:35 26 4
gpt4 key购买 nike

我想从子指令更新 Controller 变量。我更新了 Controller 变量,但该值在 View 中没有改变。我需要使用 $scope.$apply() 吗? $摘要?

这是我的代码 http://plnkr.co/edit/zTKzofwjPfg9eXmgmi8s?p=preview

js文件

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 元素语法是错误的。它不应该是一个不是有效 HTML 的自关闭元素。

语法应如下所示

<my-directive attr-from-parent="parentCtrl.refreshMyVar"></my-directive>

第二个也是重要的

app.controller('parentController', function($scope) {
var vm = this;
vm.myVar = 'Hello from parent';
this.refreshMyVar = function(data) {
// You should not directly refer "this" inside refreshMyVar function
// since "refreshMyVar" function is executed in context of directive
// "this" will refer "myDirective" controller scope
// console.log("this :" this); // try to uncomment and see what "this" holds
// If you use "vm" you will be able to get hold of actual "myVar" due to
// closure formed by refreshMyVar function when it was created.
// console.log("vm :" vm); // try to uncomment and see what "vm" holds
// Reading about closures(JavaScript concept) will help you.
vm.myVar = data.name;
console.log(vm);
alert('>> this.myVar ' + vm.myVar);
// Since refreshMyVar is executed in context of directive, you have do
// $apply on parent scope to apply changes
$scope.$parent.$apply();
};
});

工作中plunker

这个article也可能对你有帮助。

关于javascript - 更新 Controller 变量并在指令 View 中使用它( Angular 1.5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39802295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com