【发布时间】: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