gpt4 book ai didi

javascript - AngularJS 内部指令的绑定(bind)值更改不会反射(reflect)在外部

转载 作者:行者123 更新时间:2023-11-28 02:06:44 26 4
gpt4 key购买 nike

我正在测试内部指令中绑定(bind)变量的行为,但我似乎无法刷新 View 。模型正在根据控制台日志进行更新,我调用 $appy(),但由于某种原因 View 拒绝更新。这是jsfiddle !

这是 html

<div ng-app="foo">
<div ng-controller="MyCtrl">
<div my-directive val="val" checked="checked" refresh="refresh"></div>
<p>val (outside directive): {{val}}<p/>
<p>checked (outside directive): {{checked}}<p/>
</div>
</div>

这是 JavaScript

angular.module('foo', []).directive('myDirective', function() {
return {
restrict: 'A',
scope: {
val: "=",
checked: "=",
refresh: "="
},
template: '<p>val (inside directive): {{val}}</p>' +
'<p>checked (inside directive): {{checked}}</p>' +
'<input type="checkbox" ng-model="checked">checked',
link: function(scope, element, attrs) {
var count = 0;
//scope.val = "initialized";
scope.$watch('checked', function() {
scope.val = "new value" + count;
count += 1;
console.log("updated val is: " + scope.val);
scope.refresh();
});
} // link
}; // return
}); // angular.module

function MyCtrl($scope) {
$scope.val = "initial value";
$scope.checked = false;
$scope.$watch('val', function(newVal) {
console.log("newVal is: " + newVal);
});
$scope.refresh = function() {
// none of the following lines make a difference
if(!$scope.$$phase) $scope.$apply();
// $scope.$apply();
// if(!$scope.$$phase) $scope.$digest();
// $scope.$digest();
console.log("val is: " + $scope.val);
console.log("checked is: " + $scope.checked);
}; // refresh
} // MyCtrl

最佳答案

如果您只需将 fiddle 中的 angularjs 版本从 1.1.1 更改为 1.2.1,就可以了。

关于javascript - AngularJS 内部指令的绑定(bind)值更改不会反射(reflect)在外部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17661510/

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