我对 Angular 很陌生(第 3 天)。我有以下看法:
<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()
}
)