2016-09-26 47 views
2

我正在使用Angular ui-select來創建「搜索和選擇組件」。當用戶鍵入搜索字段時,它會立即將項目列表篩選爲自由文本過濾器。此外,用戶可以從下拉菜單中選擇選項,這些選項在過濾器中用作精確的搜索詞(例如按類別過濾)。如何將回調傳遞給擴展現有指令的Angular指令?

我創建了一條額外的指令,該指令擴展了<ui-select>以訪問該範圍內的$select.search值。該變量包含用戶鍵入的自由文本。我的問題是,我怎麼能傳遞給父控制器?

理想情況下,我想類似如下:

<ui-select 
    my-ui-select 
    on-search-changed="searchChanged(newValue, oldValue)" 
    multiple 
    ng-model="ctrl.myModel"> 
    <!-- ... --> 
</ui-select> 

我的自定義指令將調用on-search-changed回調與自由文本值。問題是我無法爲my-ui-select指令定義範圍,因爲它會與ui-select範圍發生衝突。

如何將回調方法傳遞給我的自定義指令,同時仍然能夠訪問ui-select範圍?或者有更好的方法來實現我所追求的目標?我建立了a Plunker based on the ui-select examples。我已經定義了myUiSelect指令,它使用console.log來輸出搜索條件。我想要的是從那裏撥打DemoCtrl.searchChanged方法。

回答

0

在您的自定義指令中,您的call on-search-changed回調函數可以發出帶有$ emit的事件。 文檔約$ emit

通過作用域層級通知 註冊$ rootScope.Scope聽衆向上將事件調度名。

所以,你可以這樣做:

$scope.$emit("mySelectEventThing", "Hey this is the value I want to emit"); 

而且在你的父母範圍/控制器,你可以監聽事件:

$scope.$on("mySelectEventThing", function(event, theValue) { 
    alert(theValue); // alert with 'Hey this is the value I want to emit' 
}); 

$ emit廣播向上到父作用域。 $ broadcast向下發送給所有子範圍。如果您有很多範圍,$廣播的性能會更高一點。你可能不需要這個。

發送事件是Angular將數據正確傳遞到另一個作用域的唯一方法。

您也可以通過使用$ scope。$ parent來達到父範圍,但這是非常不好的練習,因爲您無法確保達到預期範圍。

0

我認爲你應該改變你的方法,而不是在你的指令中擴展ui選擇,你應該把它包裝在yoru指令中,並將你的控制器中的函數傳遞給指令。

代碼指令

app.directive('myUiSelect', function() { 
    return { 
    templateUrl:'myUiSelect.html', 
    scope:{ 
     onSearchChanged:'=', 
     selectedItem:'=', 
     items:'=' 
    }, 
    link: function(scope, element, attrs, $select) { 
    scope.selectedItemModel = { 
     selectedItem:[] 

    } 
    scope.onSelectCallback = function(item, selectedItems){ 

    scope.onSearchChanged(scope.selectedItemModel.selectedItem, item) 

    } 
    } 
}; 
}) 

HTML部分(myUiSelect.html)

<ui-select multiple 
     ng-model="selectedItemModel.selectedItem" 
     theme="bootstrap" 
     ng-disabled="ctrl.disabled" 
     sortable="true" 
     on-select="onSelectCallback($item, $model)" 
     close-on-select="false" 
     style="width: 800px;"> 
<ui-select-match placeholder="Select person...">{{$item.name}} &lt;{{$item.email}}&gt;</ui-select-match> 
<ui-select-choices repeat="person in items | propsFilter: {name: $select.search, age: $select.search}"> 
    <div ng-bind-html="person.name | highlight: $select.search"></div> 
    <small> 
    email: {{person.email}} 
    age: <span ng-bind-html="''+person.age | highlight: $select.search"></span> 
    </small> 
</ui-select-choices> 
</ui-select> 

這裏是工作Plunker

請讓我知道,如果我的這個問題的認識是錯誤的