使用指令中NG-模型 [英] Using ng-model within a directive
问题描述
我有在angularjs自定义定义指令。基本上我希望发生的是用户将从一个选择框选择一个值,这将一个值追加到数组。这导致我的自定义指令调用并呈现在屏幕上一个新的元素。我想该指令生成绑定到控制器的属性的文本字段。
I've got a custom defined directive in angularjs. Basically what I want to happen is the user will pick a value from a select box and that will append a value to an array. This causes my custom directive to be invoked and render a new element on the screen. I want the text field that the directive generates to bind to the controller's attribute.
HTML
<device-list ng-repeat="device in devices" key="device.key" display-name="device.display_name" bind-prefix="descriptions"></device-list>
指令
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)
}
}
})
控制器
function DevicesCtrl($scope) {
descriptions = {}
}
看来好像是NG-模式是本地指令的范围,我怎么做它应用到父?如果我有在页面上一堆文本字段像
It appears as though as ng-model is local to the directive's scope, how do I make it apply to the parent? If I have a bunch of text fields on the page like
<input ng-model="descriptions.test"/>
它的工作原理的作品,除了由选择框产生的磁场。
It works works except with the fields generated by the select box.
推荐答案
好吧,我想通了。它涉及到传递的'='我的父属性(由托什建议)。我也不得不做出$调用编译,使其认识到NG-模式指令。下面是完整的code,我敢肯定有办法做到这一点,但清洁我很高兴有它的工作。
Ok, I figured it out. It involved passing in my parent attribute as '=' (suggested by Tosh). I also had to make a call to $compile to make it recognize the ng-model directive. Here's the full code, I'm sure there's a way to do this cleaner but I'm just glad to have it working.
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)
}
}
})
这篇关于使用指令中NG-模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!