我在angularjs中有一个自定义指令.基本上我想要发生的是用户将从选择框中选择一个值,并将值附加到数组.这会导致我的自定义指令被调用并在屏幕上呈现一个新元素.我希望指令生成的文本字段绑定到控制器的属性.
HTML
<device-list ng-repeat="device in devices" key="device.key" display-name="device.display_name" bind-prefix="descriptions"></device-list>
Run Code Online (Sandbox Code Playgroud)
指示
angular.module('device_list_tag', []).
directive('deviceList', function() {
return {
restrict: 'E',
require: '?ngModel',
scope: {
devices: '=',
key: '=',
displayName: '=',
bindPrefix: '@'
},
link: function(scope, element, attrs) {
var deviceListElement = $(element)
var containerDiv = $('<div>')
.addClass('row')
var labelTag = $('<label>').text(scope.displayName)
.addClass('span1')
var bindField = attrs.bindPrefix+'.'+scope.key
var textField = $('<input>')
.addClass('span3')
.attr('ng-model', bindField)
containerDiv.append(labelTag)
containerDiv.append(textField)
deviceListElement.append(containerDiv)
}
}
})
Run Code Online (Sandbox Code Playgroud)
调节器
function DevicesCtrl($scope) {
descriptions = {}
}
Run Code Online (Sandbox Code Playgroud)
似乎ng-model是指令范围的本地,我如何将其应用于父级?如果我在页面上有一堆文本字段,就像
<input ng-model="descriptions.test"/>
Run Code Online (Sandbox Code Playgroud)
它的工作原理除了选择框生成的字段外.
好的,我明白了.它涉及将我的父属性传递为'='(由Tosh建议).我还必须调用$ compile以使其识别ng-model指令.这是完整的代码,我确信有一种方法可以做到这一点,但我很高兴让它工作.
angular.module('device_list_tag', []).
directive('deviceList', function($compile) {
return {
restrict: 'E',
scope: {
devices: '=',
key: '=',
displayName: '=',
bindAttr: '=' // added
},
link: function(scope, element, attrs) {
console.log(scope)
var deviceListElement = $(element)
var containerDiv = $('<div>')
.addClass('row')
var labelTag = $('<label>').text(scope.displayName)
.addClass('span1')
var bindField = 'bindAttr.'+scope.key
var textField = $('<input>')
.addClass('span3')
.attr('ng-model', bindField)
$compile(textField)(scope) // added
containerDiv.append(labelTag)
containerDiv.append(textField)
deviceListElement.append(containerDiv)
}
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14603 次 |
| 最近记录: |