为什么在指令属性上使用$ watch不起作用?

时间:2014-10-22 14:04:31

标签: angularjs angularjs-directive angularjs-scope angularjs-controller

我有指令使用另一个指令设置他的属性' gridWidth'但是我试图观察该属性发生变化而它根本不起作用。谁能解释我做错了什么?

angular.module('myApp')
        .directive('myGrid', function () {
            'use strict';
            return {
               restrict: 'E',
               replace: true,
               scope: {
                   gridWidth: '='
               },
               controller: ['$scope', function(scope) {

                    scope.$watch('gridWidth', function (newValue, oldValue) {
                       console.log("width is changed");
                   }, true);

                }],
                template: '<div element-resize gridWidth="{{windowWidth}}"></div>'

            };
        });

&#39; windowWidth&#39; 变化正常,我可以在HTML dom更改中看到它,但$ watch因某些原因无法工作,所以我无法做任何事情什么时候更新。这是另一个更新第一个宽度为:

的指令
angular.module('myApp')
    .directive('elementResize', function () {
    'use strict';
        return {
            restrict: 'A',
            controller: ['$scope', '$element', function($scope, $element) {

            $scope.getElementDimensions = function () {
               return { 'h': $element.height(), 'w': $element.width() };
            };

            $scope.$watch($scope.getElementDimensions, function (newValue, oldValue) {
                $scope.windowHeight = newValue.h;
                $scope.windowWidth = newValue.w;
            }, true);
        }]
        };
    });

0 个答案:

没有答案
相关问题