将对象传递给Angular指令属性不通过

时间:2016-02-01 16:28:04

标签: javascript angularjs

我正在通过JavaScript对象传递给Angular.js指令。在attrs函数中记录link时,我会在那里看到我的属性,但在记录attrs.myOptions时没有数据:

var directive = function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      myOptions: '='
    },
    link: function(scope, element, attrs) {
      console.log(scope)
      console.log(attrs)
      console.log(attrs.myOptions)
    }
  }
}

我正在我的模板中实现它:

<directive my-options="myObject" />

myObject是一个JavaScript对象,它在模板的控制器中设置。

我在控制台中收到此错误:

Syntax Error: Token 'myObject' is unexpected, expecting [:] at column 3 of the expression [{{myObject}}] starting at [myObject}}].

1 个答案:

答案 0 :(得分:4)

如上所述,您可以像这样使用。只更改您必须通过范围访问模型。

&#13;
&#13;
var myApp = angular.module('myApp', []);	

myApp.directive("directive",function() {
  return {
	restrict: 'E',
	replace: true,
	scope: {
	  myOptions: '='
	},
	link: function(scope, element, attrs) {
	  console.log(scope)
	  console.log(attrs)
	  console.log(scope.myOptions)
	}
  }
});
myApp.controller('myCtrl', function($scope) {
		$scope.myObject = [1,2,3,4,5];
	console.log("app controller");
});
&#13;
<!doctype html>
<html>
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>   

<head>
</head>

<body>
  <div ng-app="myApp" ng-controller="myCtrl">    
	<directive my-options="myObject" />
</div>
</body>

</html>
&#13;
&#13;
&#13;