1

我正在测试内部指令中绑定变量的行为,但我似乎无法刷新视图。模型正在根据控制台日志进行更新,我调用了 $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
4

1 回答 1

1

如果您只需将小提琴中的 angularjs 版本从 1.1.1 更改为 1.2.1,它就可以工作。

于 2013-12-15T12:56:50.457 回答