Angularjs 指令在变量和 css 属性 之间实时绑定
Angularjs directive live binding between variable and css property
如果我更改控制器变量(变量包含以 px 为单位的高度,比方说 445)。
问题是,指令中的变量总是未定义的。
我也试过 $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 值。
非常感谢任何帮助。
您需要将侧高从控制器传递到指令中,如下所示:
<div ng-app="ctrl">
<div ng-controller="TempCtrl">
<span temp-directive sideheight="sideheight">here we go</span>
</div>
</div>
指令的作用域不从控制器继承侧高,您必须告诉指令侧高属性采用什么属性或控制器上的值。
如果我更改控制器变量(变量包含以 px 为单位的高度,比方说 445)。
问题是,指令中的变量总是未定义的。 我也试过 $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 值。
非常感谢任何帮助。
您需要将侧高从控制器传递到指令中,如下所示:
<div ng-app="ctrl">
<div ng-controller="TempCtrl">
<span temp-directive sideheight="sideheight">here we go</span>
</div>
</div>
指令的作用域不从控制器继承侧高,您必须告诉指令侧高属性采用什么属性或控制器上的值。