对象不能在指令中分配

问题描述 投票:0回答:1

In this plunk我有一个包装div的指令。当div条件为真时显示ng-if(单击按钮设置)。

该指令有一个范围元素css,它是一个对象,其中对象具有属性width。问题是Angular在显示指令时会抱怨;单击按钮时,在控制台中看到以下错误消息:

与指令'modal'一起使用的属性'css'中的表达式'{width:width}'是不可赋值的!

请注意,当删除指令中的$timeout时,此问题就会消失,但我无法丢弃它。

为什么会发生这种情况以及如何解决它(保持$timeout)?

HTML

<button ng-click="open()">Open modal</button>
<div modal ng-if="showModal" css="{ width: width}">
    <p>some text in modal</p>
</div>

使用Javascript

angular.module("app", [])

.controller('ctl', function($scope) {

  $scope.width = '200px';
  $scope.open = function(){
    $scope.showModal = true;
  };
})

.directive("modal", function($timeout) {

    var directive = {};

    directive.restrict = 'EA';

    directive.scope = { css: '=' };

    directive.templateUrl = "modal.html";

    directive.link = function (scope, element, attrs) {

            $timeout(function(){
                 scope.css.height = '100%';
            },100);

     };

     return directive;

});

模板

<style>
#modaldiv{
  border:2px solid red;
}
</style>
<div id="modaldiv" ng-style="{'width': css.width,'height': css.height}">
    Some content
</div>
angularjs angularjs-directive
1个回答
1
投票

由于您没有将范围变量传递给css属性,因此会出现错误。

您可以通过创建一个在ctrl中保存css的变量并将此变量传递给css属性来解决此问题。

调节器

$scope.css = {width: $scope.width};

HTML

<div modal ng-if="showModal" css="css">
    <p>some text in modal</p>
</div>

或者在指令中创建css的本地深层副本,并在$timeout中操作副本。

指示

directive.link = function (scope, element, attrs) {
    scope.cssCopy = angular.copy(scope.css);
    $timeout(function(){
        scope.cssCopy.width = '100%';
    }, 100);
};

模板

<div id="modaldiv" ng-style="{'width': cssCopy.width,'height': cssCopy.height}">
    Some content
</div>
© www.soinside.com 2019 - 2024. All rights reserved.