我对角很陌生(第三天)。我有以下看法:
<div ng-repeat="keyword in vc.promotionData.keywords">
<keyword data="keyword"></keyword>
</div>我的keyword指令如下:
promotionApp.directive("keyword", ->
template = """
<span class="input-append">
<input type="text" value="{{data.value}}" ng-model="_value"
placeholder="Add Search Keyphrase (3-5 words)" class="span12"
id="appendedInputButton">
<button class="btn" type="button" ng-click="saveKeyword({{data.id}}, {{data.promotion_id}}, _value)">Save</button>
<button class="btn" type="button" ng-click="saveKeyword({{data.id}}, {{data.promotion_id}}, _value)">Delete</button>
</span>
"""
return {
restrict: "E"
transclude: true
template: template
replace: true
scope: {}
controller: ($scope, $element, $attrs) ->
$scope.data = $attrs.data
$scope.saveKeyword = (id, promotion_id, value) ->
value ?= ""
if id and promotion_id
if value.length is 0
console.log "saveKeyword::delete"
else
console.log "saveKeyword::save #{value}"
}
)因此,我想要做的是,从我的HTML视图中,将keyword对象传递给指令(关键字是JSON)。
在向指令中添加控制器之前,我可以这样做:
scope: { data:"=" }但是对控制器来说,它不起作用。因此,我的问题是,我现在如何将keyword对象从HTML中导入到其控制器中的keyword指令$scope中?
编辑:实际上,范围和控制器是协同工作的。是我的错。
promotionApp.directive("keyword", ->
template = """
<span class="input-append">
<input type="text" ng-model="data.value"
placeholder="Add Search Keyphrase (3-5 words)" class="span12"
id="appendedInputButton">
<button class="btn" type="button" ng-click="saveKeyword(data.id, data.promotion_id, data.value)">Save</button>
<button class="btn" type="button" ng-click="saveKeyword(data.id, data.promotion_id, '')">Delete</button>
</span>
"""
return {
restrict: "E"
transclude: true
template: template
replace: true
scope: { data:"=" }
controller: ($scope, $element, $attrs) ->
console.log $scope.data
$scope.saveKeyword = (id, promotion_id, value) ->
value ?= ""
console.log "#{id} #{promotion_id} #{value} "
if id and promotion_id
if value.length is 0
console.log "saveKeyword::delete"
else
console.log "saveKeyword::update"
else if promotion_id and value.length > 0
console.log "saveKeyword::create"
$element.remove()
}
)发布于 2013-09-29 15:35:21
如果您设置了scope: { data:"=" },那么就不应该设置$scope.data = $attrs.data。实际上,如果您设置了$scope.data = $attrs.data,那么您将$scope.data设置为"keyword"的字符串值,而不是对象。
通过使用scope: {data: '='},$scope.data将被绑定,并将通过对data的任何更改进行更新。
另外,不要假设在初始化控制器代码时将设置$scope.data。取决于它的用途,它可能存在,也可能不存在。
一旦发生data绑定,模板就会绑定到'='。
https://stackoverflow.com/questions/19079578
复制相似问题