javascript - AngularJS 中的链接选项

标签 javascript angularjs angularjs-directive window-resize

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

脚本

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>

使用上面的代码,我无法将调整大小事件与元素绑定(bind)。 我想在调整窗口大小时更新宽度。 您能帮我找到解决方案并提供代码重构建议吗?

帮助将不胜感激。提前致谢!!

最佳答案

您需要在指令链接内使用 window.onresize 函数,然后高度更改逻辑将位于其中,但如果您想以 Angular 方式执行此操作,则需要使用 $window Angular 的 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();
            });
        }
    }
});

希望这可以帮助你。谢谢。

关于javascript - AngularJS 中的链接选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28527086/

相关文章:

javascript - Angular Material md-select 不显示错误

javascript - 通过模型初始化日期时间选择器上的日期

javascript - 在 AngularJs 中单击时选择和取消选择所有复选框

javascript - Angular 1.5 组件与旧指令 - 链接函数在哪里?

javascript - Angular JQuery Datepicker 未在加载时设置 MinDate

javascript - 在( Angular 6)中的不同域之间共享 LocalStorage/SessionStorage

javascript - 如何让nodejs在没有端口号的情况下在Apache服务器上运行

c# - 打印 <div> 标签内的图表

javascript - Angular .js : How to use ng-href in template?

javascript - 在 Angular 中动态创建元素