简体   繁体   English

将指令范围与AngularJS中的控制器绑定

[英]Binding directive scope with controller in AngularJS

I'm using a directive to check how much the user is scrolling the window but I can't manage to bind the scope with the controller. 我正在使用指令来检查用户正在滚动窗口多少,但是我无法设法将范围与控制器绑定。

Here's the directive and controller code: 这是指令和控制器代码:

'use strict';

angular.module('myApp.landing', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
}])
.controller('landingCtrl', ["$scope", function($scope) {
    $scope.scrolled = false;

    $scope.$on('$routeChangeSuccess', function() {
    });
}]).
directive("scroll", ["$window", function($window){
    return {
        scope: false,
        link: function($scope, element, attrs){
            angular.element($window).bind("scroll", function(){
                if (this.pageYOffset >= 150) {
                     $scope.scrolled = true;
                     console.log($scope.scrolled + 'Scrolled 100px');
                 } else {
                     $scope.scrolled = false;
                     console.log($scope.scrolled + 'Not scrolled enough');
                 }
            });
        }
    };
}]);

this is the view code: 这是视图代码:

<div ng-controller="landingCtrl" scroll>
    <div class="row">
        <div class="col-sm-12 col-md-9 landing-square">{{ scrolled }}</div>
        <div class="col-sm-12 col-md-3 landing-square"></div>
        ....
</div>

In the view scrolled is not defined. 在视图中未定义滚动。 If I define it in the controller I can see it, but the directive can't change its value. 如果在控制器中定义它,则可以看到它,但是指令不能更改其值。 Basically I want in the view the variable "scrolled" that is changing value according to the directive. 基本上,我希望在视图中根据指令更改值的“ scrolled”变量。

What am I missing? 我想念什么?

Because you're changing a something on the scope in a place Angular does not "know" about (eg a custom DOM event handler), you need to explicitly tell it to apply that change: 因为您正在更改Angular所不知道的地方的范围中的某物(例如,自定义DOM事件处理程序),所以您需要明确地告诉它应用该更改:

angular.element($window).bind("scroll", function(){
    if (this.pageYOffset >= 150) {
         $scope.$apply(function() { $scope.scrolled = true; });
         console.log($scope.scrolled + ' Scrolled 100px');
     } else {
         $scope.$apply(function() { $scope.scrolled = false; });
         console.log($scope.scrolled + ' Not scrolled enough');
     }
});

See this example , and see this excellent Q&A on $scope $apply and $watch . 请参见本示例 ,并$scope $apply$watch上进行$scope出色的问答 Or just go straight to the relevenat documentation (which is dry/technical, but explains the reasoning bhind it as well). 或直接进入relevenat文档 (该文档是干燥的/技术性的,但也说明了其背后的原因)。

In the directive, you are changing the scope values. 在指令中,您正在更改范围值。
Try to apply the changes to the scope. 尝试将更改应用到范围。

$scope.scrolled = true;     
$scope.$apply();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM