指令中无法接收隔离范围的值

时间:2015-07-06 19:35:07

标签: angularjs angularjs-directive

我创建了这个指令

angular.module('panel')
            .directive('sigPanel', sigPanel)

    function sigPanel() {
        return {
            restrict: 'E',
            scope:{
                imgData:"="
            },
            templateUrl: 'app/widgets/signature/signature.html',
            link: function (scope, element, attrs) {
                console.log(scope.imgData);
            }
        }
    }

这是templateURL:

<canvas style="border:1px solid black;"></canvas>

并将其添加到HTML中:

<sig-panel imgData="test"></sig-panel>

控制台日志仅输出&#34;未定义&#34;,不应该记录&#34;测试&#34;?我知道指令html标签工作正常,因为画布出现在页面上,但是为什么该指令不会获得&#34; imgData&#34;的价值?

如果我尝试在指令中设置scope.imgData,我会收到错误

[$compile:nonassign] Expression 'undefined' used with directive 'signaturePanel' is non-assignable!

不确定为什么会这样。

1 个答案:

答案 0 :(得分:0)

您需要将imgData(camelCase规范化)更改为img-data(划线分隔)。如果你想传递字符串&#34; test&#34;在你需要的范围内加上引号。

&#13;
&#13;
angular.module('app', []).directive('sigPanel', sigPanel);

function sigPanel() {
  return {
    restrict: 'E',
    scope: {
      imgData: "="
    },
    template: '<canvas style="border:1px solid black;"></canvas>',
    link: function(scope, element, attrs) {
      console.log(scope.imgData);
    }
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app='app'>

  <sig-panel img-data="'test'"></sig-panel>

</div>
&#13;
&#13;
&#13;

可分配示例:

&#13;
&#13;
angular.module('app', [])
.controller('myController', function($scope) {
  $scope.test = 'test';
})
.directive('sigPanel', sigPanel);

function sigPanel() {
  return {
    restrict: 'E',
    scope: {
      imgData: "="
    },
    template: '<canvas style="border:1px solid black;"></canvas>',
    link: function(scope, element, attrs) {
      console.log(scope.imgData);
      scope.imgData = 'bob';
      console.log(scope.imgData);
    }
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app='app' ng-controller='myController'>
  <sig-panel img-data="test"></sig-panel>
  {{ test }}
</div>
&#13;
&#13;
&#13;