指令中的作用域变量未定义

scope variable undefined in directives

本文关键字:变量 未定义 作用域 指令      更新时间:2023-09-26

我正在使用指令,我想在指令内使用范围变量,但它正在抛出未定义的错误。

我想循环与固定的数字?所以我试着这里的项目是未定义的错误,我得到?

是否有其他方法来迭代循环?多少次??

HTML:

<my-dir 
        bgcolor="#EFF"
        my-title="abdullah" 
        my-height="190"
        my-width="160"
        my-color="red"            
        my-bgcolor="blue"
        my-collapseoption=true
        my-widgetno="1"
        save="saveChanges('custom directive')">template
      </my-dir>

脚本:

var app = angular.module('myApp',  ['ngAnimate']);
app.controller('MyCtrl', function($scope, $http) {
   $scope.items = ['a','b','c'];
    });
// add a directive
app.directive("myDir", function() {
  return {
    restrict: "E",
    scope: {
      items:"=",
      myTitle: "@",   // by value
      myHeight: "@",   // by value
      myWidth: "@",   // by value
      myColor: "@",   // by value
      myBgcolor: "@",   // by value
      myWidgetno: "@", // by reference
      myCollapseoption: "@", // by reference            
      save: "&"    // event
    },
    templateUrl:"widget.html", 
    replace: true,
    transclude: false,
    link: function (scope, element, attrs) {
        // show initial values: by-val members will be undefined
       console.log("items is " +scope.items);

        // change element just to show we can
        element.css("background", attrs.myBgcolor);
        element.css("color", attrs.myColor);
        element.css("width", attrs.myWidth+'px');
       // element.css("height", attrs.myHeight+'px');
    }
  }
});

你从未将你的items属性传递给指令,所以当指令试图访问它时,它肯定是未定义的。my-dir标记需要提供该属性。试一试:

<my-dir 
    items={{items}}
.... />