40

बुदबुदाती निम्न उदाहरण में:AngularJS - कई एनजी-क्लिक करें - घटना

<li ng-repeat="item in items" ng-click="showItem(item)"> 
    <h3>{{item.title}}</h3> 
    <button ng-click="remove(item)">Remove</button> 
    </li> 

जब मैं बटन पर क्लिक करें showItem() भी घटना के लिए बुदबुदाती वजह से शुरू हो जाती है। मुझे पता है कि मैं $event उपयोग कर सकते हैं $event.currentTarget के लिए देख सकते हैं और $event.stopPropagation() आदि करने के लिए, लेकिन यह बहुत बदसूरत है।

बीटीडब्ल्यू।

मैं कैसे रोकूँ जब मैं remove बटन पर क्लिक करें बुलाया beeing से showItem() - मैं button पर प्रचार को रोकने के लिए नहीं करना चाहते हैं (सिर्फ एक उदाहरण है यह मेरा मामले में button एक twitter bootstrapdopdown/button है)?

संपादित बदसूरत ठीक हो जाएगा करने के लिए:

function remove(item,$event){ 
    $event.originalEvent.prevent = true; 
    // rest of the code 
} 

function showItem(item,$event){ 
    if($event.originalEvent.prevent)return; 
    // rest of the code 
} 
+0

आप stopPropagation उपयोग नहीं कर सकते हैं, तो आप करना होगा अपने डोम को पुन: व्यवस्थित करें ताकि वे घोंसला न हों। क्या यह संभव है? –

उत्तर

63

यह समाधान काम किया मेरे लिए (मैं केवल हाल ही में समर्थन करने वाले ब्राउज़र कर रहा हूँ, इसलिए मैं अधिक रेट्रो-संगत होना कोड को संशोधित करने की कोशिश की):

HTML:

<li ng-repeat="item in items" ng-click="showItem(item)"> 
    <h3>{{item.title}}</h3> 
    <button ng-click="remove(item, $event)">Remove</button> 
</li> 

स्क्रिप्ट:

function remove(item, $event) { 
    // do some code here 

    // Prevent bubbling to showItem. 
    // On recent browsers, only $event.stopPropagation() is needed 
    if ($event.stopPropagation) $event.stopPropagation(); 
    if ($event.preventDefault) $event.preventDefault(); 
    $event.cancelBubble = true; 
    $event.returnValue = false; 
} 
function showItem(item) { 
    // code here 
} 

संपादित - जोड़ा गया JSFiddle डेमो इसे आज़माने के लिए http://jsfiddle.net/24e7mapp/1/

+0

इस विधि $ event.stopPropagation क्रोम संस्करण 35.0.1916.153 मीटर पर मेरे लिए काम नहीं किया था, लेकिन() किया था। मुझे $ event.returnValue की आवश्यकता नहीं थी। –

+0

बिल्कुल। (बिना 'अगर') ',' $ event.stopPropagation(): क्रोम (और अन्य आधुनिक ब्राउज़रों) में, आप पहली पंक्ति में बंद हो सकता है। लेकिन टिप्पणियों में विनिर्दिष्ट, यदि आप बनाने की जरूरत है यह IE8 एट में कम काम करते हैं, आप का उपयोग करने के '$ event.preventDefault()' या 'cancelBuble/returnValue' है। शायद उन दोनों में से एक की आवश्यकता नहीं है, मैं बिल्कुल याद नहीं कर सकता। – Tibo

+0

मेरे क्रोम पर काम नहीं करता है। – Ron

0

showItem जल्दी वापस जाने के लिए अद्यतन किया जा सकता है, तो item में पारित अब मौजूद नहीं है:

function remove(item) { 
    if (-1 == $scope.items.indexOf(item)) { 
    // Item no longer exists, return early 
    return; 
    } 
    // Rest of code here 
} 
संबंधित मुद्दे