非字符串类型AngularJS指令属性 [英] Non-string types in AngularJS directive attributes

查看:121
本文介绍了非字符串类型AngularJS指令属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个属性面板,其属性的数量可以根据所选择的对象而有所不同。

I want to create a properties pane, where the number of properties can vary depending on which object is selected.

我已经叫属性显示的名称和属性的值,使用code这样的指令创建

I have created by own directive called property that displays the name and the value of a property, using code like this:

<div ng-app="MyApp">
  <div class="properties-pane" ng-controller="PropertiesPane">
    <div ng-repeat="property in properties">
      <property name="{{property.name}}" value="{{property.value}}">
    </div>
  </div>
</div>

简单,不是吗?这只是正常,除了 property.value 将被转换为字符串(因为它是一个DOM元素的属性)。我是什么做的,如果属性值是一些其他的数据类型?例如一个对象。见实施的其余部分(在CoffeeScript中):

Simple, isn't it? This works just fine, except that property.value will be converted to a string (as it's an attribute on a DOM element). What am I to do if the property value is some other data type? For example an object. See the rest of the implementation (in Coffeescript):

MyApp = angular.module('MyApp', [])

MyApp.controller 'PropertiesPane', ($scope) ->
  $scope.properties = [
    # Note that value is an object, not a string:
    {name: 'First', value: {x:0, y:0, z:42}},
    {name: 'Second', value: {x:0, y:20, z:0}},
    {name: 'Third', value: {x:1, y:1, z:1}},
  ]

MyApp.directive 'property', ($compile) ->
  restrict: 'E'
  transclude: false
  replace: true
  scope: {name: '@name', value: '@value'}
  template: '<div>{{name}} {{value.x}}, {{value.y}}, {{value.z}}</div>'
  #                          ^^^^^^^      ^^^^^^^      ^^^^^^^
  #   this doesn't work as value is a string, not an object

正如value.x,y和z是一个字符串未定义,其结果当然是:

As value.x, y and z are undefined on a string, the result is of course:

首先,结果
二,结果
三,

First , ,
Second , ,
Third , ,

我想要的输出是:

首先0,0,42搜索
第二0,20,0结果
三1,1,1

First 0, 0, 42
Second 0, 20, 0
Third 1, 1, 1

我怀疑有某种根本性错误的,我如何编程添加元素的思考。什么是执行这样的事情Angularish方式?

I suspect there's something fundamentally wrong in my thinking of how to programatically add elements. What's the Angularish way to implement something like this?

编辑:解决方案

要通过引用,而不是作为一个字符串值,参考为对象,用 = 而不是 @ 中的指令:

To refer to value as an object by reference instead of as a string value, use = instead of @ in the directive:

scope: {name: '@', value: '='}

和模板:

<property name="{{property.name}}" value="property.value">

请注意,我删除了 {{}}

推荐答案

关于名称='property.name'范围是什么:{名:'=',值:'='}

这应该做的魔力。

要了解更多请参见和搜索(按Ctrl + F)为@,第一个结果就是你希望;)

To know more see this and search(ctrl+f) for '@', the first result is what you want ;)

这篇关于非字符串类型AngularJS指令属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆