【问题标题】:Passing object to Angular directive attributes not coming through将对象传递给 Angular 指令属性未通过
【发布时间】:2016-05-10 04:38:51
【问题描述】:

我将一个 JavaScript 对象传递给一个 Angular.js 指令。在link 函数中记录attrs 时,我在那里看到了我的属性,但是在记录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}}].

【问题讨论】:

  • 尝试在指令链接函数中通过scope.myOptions访问对象
  • 尝试用{} 封装它,就像这样my-options="{myObject}"
  • @paul147 当我登录scope 时,我看到myOptions,但是当我登录scope.myOptions 时,我得到undefined。 :(
  • 当我登录 attrs 我看到 myOptions 但值是 myObject..
  • 控制器中myObject的具体内容是什么?这个[myObject}}] 看起来像一个模板错误,但我不清楚你是如何到达那里的。

标签: javascript angularjs


【解决方案1】:

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

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");
});
<!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>

【讨论】:

    猜你喜欢
    • 2015-11-29
    • 1970-01-01
    • 2016-05-23
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    相关资源
    最近更新 更多