0

我有以下代码。由于某种原因,测试 1 失败了。谁能告诉我为什么?

angular.
    module('myModule', []).
    directive('myDirective', function () {
        return {
            restrict: 'E',
            scope: {
                myAttr: '='
            },
            link: function (scope, element, attrs) {
                element.text(scope.myAttr);
            }
        }
    });

describe('test', function () {
    var compile, rootScope;

    beforeEach(module('myModule'));

    beforeEach(inject(function ($compile, $rootScope) {
        compile = $compile;
        rootScope = $rootScope;
    }));

    describe('test 1', function () {
        it('test', function () {
            scope = rootScope.$new();

            // scope.myVar = "test";

            element = compile('<my-directive my-attr="myVar" />')(scope);
            scope.$digest();

            scope.myVar = "test";
            scope.$digest();

            expect(element.text()).toBe("test");
        });
    });

    describe('test 2', function () {
        it('test', function () {
            scope = rootScope.$new();

            scope.myVar = "test";

            element = compile('<my-directive my-attr="myVar" />')(scope);
            scope.$digest();

            scope.myVar = "test";
            scope.$digest();

            expect(element.text()).toBe("test");
        });
    });
});
4

1 回答 1

0

element.text(scope.myAttr);需要包裹在手表中,如下所示:

angular.
    module('myModule', []).
    directive('myDirective', function () {
        return {
            restrict: 'E',
            scope: {
                myAttr: '='
            },
            link: function (scope, element, attrs) {
                scope.$watch('myAttr', function () {
                    element.text(scope.myAttr);
                });
            }
        }
    });
于 2013-05-09T11:48:35.300 回答