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

最佳答案

如果您只是将小提琴中的angularjs版本从1.1.1更改为1.2.1,则它会起作用。

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

10-12 13:13