我正在测试内部指令中绑定变量的行为,我似乎无法让视图刷新。模型正在根据控制台日志进行更新,我调用$ appy(),但由于某种原因,视图拒绝更新。这是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
答案 0 :(得分:1)
如果您只是将小提琴中的angularjs的版本从1.1.1更改为1.2.1,则可以正常工作。