【问题标题】:Angularjs directive live binding between variable and css property变量和css属性之间的Angularjs指令实时绑定
【发布时间】:2015-05-20 08:07:11
【问题描述】:

如果我更改控制器变量(该变量包含以 px 为单位的高度,比如说 445),我想实时更新 HTML 中的 div 元素 css 属性(最小高度)。

问题是,指令中的变量总是未定义的。 我也试过 $watch,但还是不行。

这是一个 jsfiddle 演示: http://jsfiddle.net/xs0upf20/

这里是源代码:

<div ng-app="ctrl">
  <div ng-controller="TempCtrl">
    <span temp-directive>here we go</span>
  </div>
</div>

JS:

angular.module('ctrl', []).controller('TempCtrl', function ($scope, $location, $rootScope) {
         $scope.sideheight = 445;
     });

     angular.module('ctrl').directive('tempDirective', function () {
         return {
             restrict: 'A',
             scope: {
                 sideheight: '=sideheight'
             },
             link: function (scope, element, attrs) {
                 console.log('outside watch');
                 console.log(scope.sideheight);
                 element.css('min-height', scope.sideheight+'px');
                 scope.$watch("onlyvariable", function(newValue,oldValue,scope){
                     console.log('inside watch');
                     console.log(scope);
                 });

             }
         };
     });

sideheight 变量使用默认值初始化(我已经无法访问),稍后如果我更改变量,我希望看到更新的 css 属性。

我也试过'='、'@'绑定,还是没有成功。 使用@绑定,甚至不会在范围对象中创建变量,使用= char,它具有未定义的值。 $parent 对象确实包含 sideheight 变量,具有正确的 445 值。

非常感谢任何帮助。

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    您需要将控制器的侧高传递给指令,如下所示:

    <div ng-app="ctrl">  
        <div ng-controller="TempCtrl">
            <span temp-directive sideheight="sideheight">here we go</span>
        </div>      
    </div>
    

    指令的作用域不从控制器继承sideheight,你必须告诉指令sideheight属性在控制器上的什么属性或值。

    【讨论】:

      猜你喜欢
      • 2012-11-07
      • 1970-01-01
      • 2019-07-23
      • 2018-07-30
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多