angularjs中的链接选项

Linking option in angularjs

本文关键字:选项 链接 angularjs      更新时间:2023-11-05

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

脚本

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事件和元素绑定。每当调整窗口大小时,我都要更新宽度。你能帮我找出代码重构建议的解决方案吗。

如有帮助,不胜感激。提前感谢!!

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

指令

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();
            });
        }
    }
});

希望这能对你有所帮助。谢谢