angularjs中的链接选项

时间:2015-02-15 14:28:54

标签: javascript angularjs angularjs-directive window-resize

每当调整窗口大小时,我想更新一个表达式。 以下是我的指示,展示了我的尝试。

SCRIPT

var app = angular.module("myApp", []);
app.controller("validate", function($scope, $window) {
    $scope.outp = "hello";
});
app.directive("responsive", function($window) {
    return {
        resterict: "AE",
        link: function cLink(scope, element, attrs) {
            console.log(element);
            scope.widthe = ($window).outerWidth;
            //scope.$watch("widthe",function(newValue, oldValue){
            //scope.chnage = newValue;

            //});

            element.bind("resize", function() {
                console.log("called");
                scope.$apply();
            });
        }

    }

});

HTML

<body ng-app="myApp">
    <div ng-controller="validate" responsive>
        <div style="border:solid;width:500px;height:500px;">
            <div>present width is {{width}}</div>
            <div>{{chnage}}</div>
            <button id="clicks">click me</button>
        </div>
    </div>
</body>

使用上面的代码,我无法将resize事件与元素绑定。 我想在调整窗口大小时更新宽度。 你能帮我找一些代码重构建议的解决方案。

帮助会很感激。在此先感谢!!

1 个答案:

答案 0 :(得分:0)

您需要在指令链接中使用window.onresize函数,然后高度更改逻辑将位于其中,但如果您想以角度方式执行此操作,则需要使用$window API角度与window的角度相同。

<强>指令

app.directive("responsive", function($window) {
    return {
        resterict: "AE",
        link: function cLink(scope, element, attrs) {
            console.log(element);
            scope.width = ($window).outerWidth;
            //scope.$watch("widthe",function(newValue, oldValue){
               //scope.chnage = newValue;

            //});

            angular.element($window).bind('resize', function() {
                console.log("called");
                scope.$apply();
            });
        }
    }
});

希望这可以帮到你。感谢。